It depends upon the compiler and the optimization level. Most recent versions of GCC, on some common systems, with some optimizations, are able to do such an optimization (replacing a simple printf
with puts
, which AFAIU is legal w.r.t. standards like C99)
You should enable warnings when compiling (e.g. try first to compile with gcc -Wall -g
, then debug with gdb
, then when you are confident with your code compile it with gcc -Wall -O2
)
BTW, redefining puts
is really really ugly, unless you do it on purpose (i.e. are coding your own C library, and then you have to obey to the standards). You are getting some undefined behavior (see also this answer about possible consequences of UB). Actually you should avoid redefining names mentioned in the standard, unless you really really know well what you are doing and what is happening inside the compiler.
Also, if you compiled with static linking like gcc -Wall -static -O main.c -o yourprog
I'll bet that the linker would have complained (about multiple definition of puts
).
But IMNSHO your code is plain wrong, and you know that.
Also, you could compile to get the assembler, e.g. with gcc -fverbose-asm -O -S
; and you could even ask gcc
to spill a lot of "dump" files, with gcc -fdump-tree-all -O
which might help you understanding what gcc
is doing.
Again, this particular optimization is valid and very useful : the printf
routine of any libc has to "interpret" at runtime the print format string (handling %s
etc ... specially); this is in practice quite slow. A good compiler is right in avoiding calling printf
(and replacing with puts
) when possible.
BTW gcc
is not the only compiler doing that optimization. clang
also does it.
Also, if you compile with
gcc -ffreestanding -O2 almo.c -o almo
the almo
program shows Hello world.
If you want another fancy and surprizing optimization, try to compile
// file bas.c
#include <stdlib.h>
int f (int x, int y) {
int r;
int* p = malloc(2*sizeof(int));
p[0] = x;
p[1] = y;
r = p[0]+p[1];
free (p);
return r;
}
with gcc -O2 -fverbose-asm -S bas.c
then look into bas.s
; you won't see any call to malloc
or to free
(actually, no call
machine instruction is emitted) and again, gcc
is right to optimize (and so does clang
)!
PS: Gnu/Linux/Debian/Sid/x86-64; gcc
is version 4.9.1, clang
is version 3.4.2
c
, although the compiler invocation suggests that the code is compiled as C++. – Metabolizeprintf()
toputs()
, as the latter performs better... since you replaced the standard library puts() with a local symbol, that is what you get. If you use -O0 instead of -O2, you should actually callprintf()
– Poetstd::cout<<"hello world" << std::endl;
– Louvre