1

Ok, I'm playing a bit with a code, trying do understand some tricks and how does it work, so I don't understand output of this code

int i = 8;
printf("%d", printf("%o", i));

result of this is 102, I don't know how, I know that 8 in octal system is 10, but what most confuses me is when I put space after %o like this

printf("%d", printf("%o ", i));

now, result is 10 3, what is going on here?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

3 Answers3

5

The outer printf() will print the return value of the inner printf().

Quoting C11, chapter §7.21.6.1,

The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

So, in the first case,

 printf("%d", printf("%o", i));

the inner printf() prints 10, i.e., two characters, which is the return value of the call and the outer printf() prints that. Output of two adjacent print statements appear as 102.

Similarly, when you put a space after in the format specifier of the inner printf(), it prints (and returns) 3, so after the 10 <space>, 3 is printed.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • aah, I see, so those numbers after 10 are actually numbers of printed characters, even space counts, I understand now, thank you all for fast answers – TheNemesis584 Oct 21 '16 at 09:22
5

Printf prints to standard out, and returns int, the count of printed characters. So you get:

10 3

which is:

10 is the evaluated inner printf that prints octal 8.

and 3, the evaluated outer printf that prints the "return" value of the inner printf = 3 printed chars.

Aus
  • 1,183
  • 11
  • 27
0
int i = 8;
printf("%d", printf("%o", i));

printf returns the amount of characters it printed, which is 2 for printing 10 before. The order of evaluation means you'll get 102 as output. Or rather 10 and then 2 without a newline or space in between.

In your second example, you get 10 (notice the space) and then 3 (10 is 3 characters, {'1','0',' '}) as the return from printf.

Magisch
  • 7,312
  • 9
  • 36
  • 52