简体   繁体   English

嵌套printf状态菜单的奇怪输出

[英]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 结果是102,我不知道如何,我知道八进制的8是10,但是最让我困惑的是当我在%o之后放置空格

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

now, result is 10 3, what is going on here? 现在,结果是10 3,这是怎么回事?

The outer printf() will print the return value of the inner printf() . 外部printf()将打印内部printf()的返回值。

Quoting C11 , chapter §7.21.6.1, 引用C11 ,第§7.21.6.1章,

The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred. fprintf函数返回传输的字符数,如果发生输出或编码错误,则返回负值。

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. 内部printf()打印10 ,即两个字符,这是调用的返回值,而外部printf()打印该字符。 Output of two adjacent print statements appear as 102 . 两个相邻打印语句的输出显示为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()的格式说明符中放置一个空格后,它会打印(并返回)3,因此在10 <space> ,会打印3

Printf prints to standard out, and returns int, the count of printed characters. Printf打印到标准输出,并返回int,即已打印字符的数量。 So you get: 这样就得到:

10 3 10 3

which is: 这是:

10 is the evaluated inner printf that prints octal 8. 10是评估的内部printf,它打印八进制数8。

and 3, the evaluated outer printf that prints the "return" value of the inner printf = 3 printed chars. 3,计算出来的外部printf打印内部printf的“ return”值= 3个打印字符。

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

printf returns the amount of characters it printed, which is 2 for printing 10 before. printf返回其打印的字符数量,对于之前的10字符,该数量为2。 The order of evaluation means you'll get 102 as output. 评估顺序意味着您将获得102作为输出。 Or rather 10 and then 2 without a newline or space in between. 或者更确切地说是10 ,然后是2 ,中间没有换行符或空格。

In your second example, you get 10 (notice the space) and then 3 ( 10 is 3 characters, {'1','0',' '} ) as the return from printf . 在第二个示例中,从printf返回的结果是10 (注意空格),然后是310是3个字符, {'1','0',' '} )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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