6
int main()
{
    int a = (1,2,3);
    int b = (++a, ++a, ++a);
    int c= (b++, b++, b++);
    printf("%d %d %d", a,b,c);
}

我是编程初学者。我没有得到这个程序如何显示我的输出6 9 8

4

3 回答 3

8

,所有三个声明中使用

int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);  

逗号运算符。它计算第一个操作数1并将其丢弃,然后计算第二个操作数并返回其值。所以,

int a = ((1,2), 3);          // a is initialized with 3.
int b = ((++a, ++a), ++a);   // b is initialized with 4+1+1 = 6. 
                             // a is 6 by the end of the statement
int c = ((b++, b++), b++);   // c is initialized with 6+1+1 = 8
                             // b is 9 by the end of the statement.

1 在逗号运算符的情况下,从左到右保证评估顺序。

于 2015-12-08T11:28:22.877 回答
5

该代码无论如何都不是很好,没有人会在他们的正常头脑中编写它。你不应该花时间看那种代码,但我还是会给出解释。

逗号运算符的,意思是“做左边的,丢弃任何结果,做右边的并返回结果。将部分放在括号中对功能没有任何影响。

写得更清楚,代码将是:

int a, b, c;

a = 3; // 1 and 2 have no meaning whatsoever

a++;
a++;
a++;
b = a;

b++;
b++;
c = b;
b++;

前增量和后增量运算符的作用方式不同,这导致 b 和 c 的值不同。

于 2015-12-08T11:31:15.453 回答
1

我是编程初学者。我没有得到这个程序如何显示我的输出

只需了解逗号运算符前缀,后缀

根据提供给您的链接中提到的规则

int a = (1,2,3);          // a is initialized with 3 last argument .
int b = (++a, ++a, ++a);  // a is incremented three time so becomes 6 and b initilized with 6 . 
int c = (b++, b++, b++);  // b incremented two times becomes 8  and c initialized with  8.
                          // b incremented once more time becomes 9
于 2015-12-08T11:40:08.530 回答