[英]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- 我正在尝试在Dev C ++ IDE上运行基本代码,但是它给出了预期的输出-
printf("%d", printf("stackoverflow1"));
printf("%d", puts("stackoverflow2"));
puts(printf("stackoverflow3"));
the expected output should be: 预期输出应为:
stackoverflow114stackoverflow2
第114章
14stackoverflow314
14堆栈溢出314
but the output I'm getting is: 但是我得到的输出是:
stackoverflow114stackoverflow2
第114章
0stackoverflow3
0 stackoverflow3
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. 我知道
puts
返回一个非负数,但为什么我每次都会得到一个“ 0”。 Also in the last statement why is puts not printing the no of characters printed by printf
? 同样在最后一个语句中,为什么puts不打印由
printf
打印的字符数?
printf("%d", printf("stackoverflow1"));
Printf returns an int (how much chars are printed = 14). Printf返回一个int(打印多少字符= 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的参数,然后才能评估外部printf的字符串,所以打印的字符串将是“ stackoverflow114”
printf("%d", puts("stackoverflow2"));
puts returns a "nonnegative value" (this is the only guarantee, the standard gives to you). puts返回“负值”(这是标准给您的唯一保证)。 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
. 在您的情况下,非负值为int14。字符串“ stackoverflow2 \\ n”由
puts
打印,而14由printf
打印。
puts(printf("stackoverflow3"));
puts
takes an const char*
as an argument and printf
returns the number of chars printed (which is 14, again). puts
将const char*
作为参数,而printf
返回打印的字符数(再次为14)。 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). 由于
puts
需要一个指针,因此它可能会将地址14处的内存解释为字符串并输出(它也可能会取消编译-大多数编译器都会“高兴”并为您强制转换,并带有警告)。 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 "").
因此,此行仅打印“ stackoverflow3”(在您的情况下),而外部puts仅打印一个随机字符串(在您的情况下为“”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.