Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some one can explain this behavior ? just 2 lines of code [duplicate]

Tags:

c

Kindly explain this snippet:

#include <stdio.h>

int puts(const char *str) {
    fputs("Hello world!\n", stdout);
}

int main() {
    printf("Goodbye\n");
}

Output : Hello world! return 13

like image 417
user3626628 Avatar asked Oct 23 '14 09:10

user3626628


People also ask

What is duplicate code called?

Sequences of duplicate code are sometimes known as code clones or just clones, the automated process of finding duplications in source code is called clone detection.

Is duplicate code a code smell?

Duplicated code is considered one of the worse code smells. Beyond blatant copy paste, there are subtle duplications like parallel inheritance hierarchies and repetitive code structures.


3 Answers

It is compiler specific. You get this behavior with GCC. Here are some details.

  • since you #include <stdio.h> (actually because you are in a hosted environment) the puts is that of the C99 standard, and redefining it is undefined behavior

  • the GCC compiler has some optimizations to transform some printf to a sequence of faster puts. This is legal, since you have included <stdio.h> (and the C99 standard defines what printf should do in that case; GCC goes thru __builtin_printf as an intermediate step)

If you compile with -ffreestanding you won't observe that.

Your question is very close to this one; so this answer is also relevant.

like image 128
Basile Starynkevitch Avatar answered Dec 06 '22 22:12

Basile Starynkevitch


I compiled the program with gcc x.c -S -o-. It gave me

[...]
main:
.LFB1:
        .cfi_startproc
        pushl   %ebp
        .cfi_def_cfa_offset 8
        .cfi_offset 5, -8
        movl    %esp, %ebp
        .cfi_def_cfa_register 5
        andl    $-16, %esp
        subl    $16, %esp
        movl    $.LC1, (%esp)
        call    puts
        leave
        .cfi_restore 5
        .cfi_def_cfa 4, 4
        ret
        .cfi_endproc
.LFE1:

so indeed the printf call is replaced with puts in GCC, as they have the same semantics.

like image 33
glglgl Avatar answered Dec 06 '22 23:12

glglgl


My guess would be that the compiler changes the call to printf() into a call to puts(), since there's no need for printf() due to no formatting. Also the string is terminated by a newline, which fits puts(). The compiler didn't see your scary overload of a library function coming, so it got "fooled".

like image 27
unwind Avatar answered Dec 07 '22 00:12

unwind