相关疑难解决方法(0)

我=(i,++ i,1)+ 1; 做?

在阅读有关未定义行为和序列点的答案后,我写了一个小程序:

#include <stdio.h>

int main(void) {
  int i = 5;
  i = (i, ++i, 1) + 1;
  printf("%d\n", i);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是2.天啊,我没有看到减量来了!这里发生了什么?

另外,在编译上面的代码时,我收到一条警告:

px.c:5:8:警告:逗号表达式的左侧操作数无效

  [-Wunused-value]   i = (i, ++i, 1) + 1;
                        ^
Run Code Online (Sandbox Code Playgroud)

为什么?但可能会通过我的第一个问题的答案自动回答.

c expression operators compiler-warnings comma-operator

175
推荐指数
7
解决办法
2万
查看次数

逗号运算符如何工作

逗号运算符如何在C++中工作?

例如,如果我这样做:

a = b, c;  
Run Code Online (Sandbox Code Playgroud)

最终是否等于b或c?

(是的,我知道这很容易测试 - 只是在这里记录,以便有人快速找到答案.)

更新: 此问题在使用逗号运算符时暴露了细微差别.只是记录下来:

a = b, c;    // a is set to the value of b!

a = (b, c);  // a is set to the value of c!
Run Code Online (Sandbox Code Playgroud)

这个问题实际上是受到代码中的拼写错误的启发.打算做什么

a = b;
c = d;
Run Code Online (Sandbox Code Playgroud)

转换成

a = b,    //  <-  Note comma typo!
c = d;
Run Code Online (Sandbox Code Playgroud)

c++ comma-operator

165
推荐指数
6
解决办法
5万
查看次数