理解逗号运算符

前端之家收集整理的这篇文章主要介绍了理解逗号运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. int main()
  2. {
  3. int a = (1,2,3);
  4. int b = (++a,++a,++a);
  5. int c= (b++,b++,b++);
  6. printf("%d %d %d",a,b,c);
  7. }

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

解决方法

用于所有三个声明
  1. int a = (1,3);
  2. int b = (++a,++a);
  3. int c = (b++,b++);

它是comma operator.它计算第一个操作数1并丢弃它,然后计算第二个操作数并返回其值.因此,

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

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

猜你在找的C&C++相关文章