Here is my test code:
#include<stdio.h>
static inline void foo(int a){
printf("%x\n", a);
}
int main(void){
foo(0x1234);
return 0;
}
I thought GCC should realize that a
is a literal integer, and optimize to code like this:
puts("1234");
But I got the following assembly code:
│0x8048341 <main+17> push $0x1234
│0x8048346 <main+22> push $0x80484e0
│0x804834b <main+27> push $0x1
│0x804834d <main+29> call 0x8048310 <__printf_chk@plt>
There exists a lot of such code in my project, because I always believed that GCC would optimize for me, and even in some context where could simply use 'write()', I insisted using printf
, because I thought I would gain benefit from its buffer mechanism.
Now I feel regret, for the overhead of paring a format string will kill any gain I have. These codes in my project are quite low-level, and they might cause the performance bottleneck.
printf()
has side-effects the compiler can't know about at the compile stage.printf()
is define by C standard.int
for%x
may be well-defined, asva_arg
allows mixing signedness (7.15.1.1 in C99). GCC and Clang seem to agree with this interpretation, as they don't warn even with-Wformat=2
.printf
. Maybe in a couple of years we'll get it? :)