简体   繁体   English

为什么此C程序的此输出?

[英]Why this output of this C program?

Program: 程序:

   int main( )
    {
    printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));
    return 0;
    }

Output: 输出:

5 57 73

I am new to C, I could guess where the 5 57 7 came from, but no idea where the 3 came from. 我是C语言的新手,我想知道5 57 7的来源,但不知道3的来源。 Can someone explain the output? 有人可以解释输出吗?

If you apply binary AND to 3 and 3 (which are the return values of both nested printf calls) you get 3 as result. 如果将二进制AND应用于33 (这是两个嵌套printf调用的返回值),则结果为3

Note that the code actually contains undefined behaviour, since the order of the nested calls isn't defined. 请注意,该代码实际上包含未定义的行为,因为未定义嵌套调用的顺序。

The return value of the printf function is the number of characters transmitted, or a negative value if there is an error. printf函数的返回值是传输的字符数,如果有错误,则返回负数。

printf("%d %d",5,5) returns 3 if there is no error 如果没有错误printf("%d %d",5,5)返回3

printf("%d %d",7,7) also returns 3 if there is no error 如果没有错误printf("%d %d",7,7)也会返回3

So printf("%d %d",5,5) & printf("%d %d",7,7) is 3 & 3 which is evaluated to 3 . 因此printf("%d %d",5,5) & printf("%d %d",7,7)3 & 3 ,其求值为3

3 is the Bitwise AND of the values returned by two printf. 3是两个printf返回的值的按位与

printf returns the numbers of characters printed. printf返回打印的字符数。 In your case, printf("%d %d",5,5) has printed three characters that are two 5 and one space, similarly printf("%d %d",7,7) is also printing two 7 and one space. 在您的情况下, printf("%d %d",5,5)已打印三个字符,即两个5和一个空格,类似地printf("%d %d",7,7)也打印了两个7和一个空间。 Hence both printf is returning 3. 因此,两个printf都返回3。

so, 3 is the result of 3 & 3 所以3是3 & 3的结果

as you can see here : http://en.wikipedia.org/wiki/Printf_format_string , printf return the number of printed chars, so: 如您在此处看到的: http : //en.wikipedia.org/wiki/Printf_format_string,printf返回已打印字符的数量,因此:

printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));

is composed of : 由...组成 :

printf("%d %d",5,5) return 3 (5 space and 5) and print 5 5

printf("%d %d",7,7) return 3 (7 space and 7) and print 7 7

At this stage we got : 5 57 7 在这一阶段,我们得到了: 5 57 7

And 3 & 3 = 3 , finally you got this output: 3 & 3 = 3 ,最终您得到以下输出:

5 57 73

Regards. 问候。

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

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