简体   繁体   中英

Strange output from nested printf statemenets

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?

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 , ie, 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.

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.

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 .

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