简体   繁体   中英

Unexpected output on using puts() and printf() function

I'm trying to run a basic code on my Dev C++ IDE, but it gives an expected output-

printf("%d", printf("stackoverflow1"));
printf("%d", puts("stackoverflow2"));
puts(printf("stackoverflow3"));

the expected output should be:

stackoverflow114stackoverflow2

14stackoverflow314

but the output I'm getting is:

stackoverflow114stackoverflow2

0stackoverflow3

Can someone explain the inconsistency in the output ? I know that puts return a non negative number but why I'm getting a '0' everytime. Also in the last statement why is puts not printing the no of characters printed by printf ?

  • puts(), as you mentioned, only has to return a non-negative number on success. This means the compiler you are using gets to decide what is returned, as long as it follows this. Your compiler appears to have chosen 0.
  • as 2501 mentioned, passing puts(const char * p ) an int is illegal, your compiler should have complained about it. puts() is supposed to print starting from p until it reaches a '\\0' char, so the input has to be a pointer to a '\\0' terminated string

You have undefined behavior. puts() takes a const char* argument yet you pass it an int .

puts(printf("stackoverflow3"));

Enable warnings on your compiler and your code won't even compile.

printf("%d", printf("stackoverflow1"));

Printf returns an int (how much chars are printed = 14). Because the arguments of the outer printf have to be evaluated before the outer one can be evaluated, the string printed will bee "stackoverflow114"

printf("%d", puts("stackoverflow2"));

puts returns a "nonnegative value" (this is the only guarantee, the standard gives to you). In your case the nonnegative value is the int 14. The string "stackoverflow2\\n" is printed by puts and the 14 is printed by printf .

puts(printf("stackoverflow3"));

puts takes an const char* as an argument and printf returns the number of chars printed (which is 14, again). Since puts takes a pointer, it may interpret the memory at address 14 as a string and output it (it might cancel compilation, too - most compilers will be 'glad' and cast this for you, along with a warning). This string seems to be empty (this might be sort of random). This line thus only prints "stackoverflow3" (in your case) and the outer puts only prints a random string (in your case "").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM