Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only the first printf is outputted to the terminal?

Tags:

c

I have a C program where I define and use my own printf() function. However, only the first printf, i.e. printf("Hello World 1\n"); is outputted. But why?

int printf(const char *__restrict __format, ...);

int printf(const char *__restrict __format, ...) {}

int main() {
    printf("Hello World 1\n");
    printf("Hello World %d\n", 2);
    return 0;
}

the output is:

Hello World 1

But I don't understand why

like image 916
Ziao Li Avatar asked Oct 28 '25 04:10

Ziao Li


1 Answers

According to §7.1.3 of the ISO C11 standard, the identifier printf is reserved for use by the standard library. This applies even if you do not include the header file, because the identifier has external linkage. Therefore, as far as the ISO C standard is concerned, your program is invoking undefined behavior, which means that anything can happen, including the behavior you describe.

However, if you are asking why specifically the compiler gcc behaves this way, then the answer is a bit more complex, because the compiler gcc has its own rules:

In gcc, the function printf is a built-in function. This allows the compiler to optimize the line

printf("Hello World 1\n");

to:

puts("Hello World 1");

It does not perform this optimization on printf calls with more than one argument, so the line

printf("Hello World %d\n", 2);

does not get optimized to puts.

Therefore, your posted code effectively gets compiled to the following:

int printf (const char *__restrict __format, ...);

int printf (const char *__restrict __format, ...) {}

int main() {
    puts("Hello World 1");
    printf("Hello World %d\n", 2);
    return 0;
}

If you want to prevent gcc from optimizing printf calls to puts calls, then you can use the -fno-builtin command-line option to prevent gcc from recognizing functions as built-in, or -fno-builtin-printf to only prevent the printf function from being recognized as built-in. Note that even if you use these options, you can still explicitly call the built-in versions of these functions by using the __builtin_ prefix, for example __builtin_printf.

like image 104
Andreas Wenzel Avatar answered Oct 29 '25 19:10

Andreas Wenzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!