1

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 ?

2
  • '0' is a non-negative number. It was never said it should be the number of characters printed. Commented Dec 10, 2014 at 8:23
  • puts(printf("stackoverflow3")); invokes UB. Commented Dec 10, 2014 at 9:58

3 Answers 3

3
  • 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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

-1
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 "").

1 Comment

"it will interpret the memory at address 14 as a string " - your answer should note that this is a compiler extension (not a very good one either IMHO); in Standard C the code is ill-formed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.