逗号运算符如何在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) 我们可以写一个if声明
if (a == 5, b == 6, ... , thisMustBeTrue)
Run Code Online (Sandbox Code Playgroud)
只有最后一个条件才能进入if身体.
为什么允许?
我以前从未见过这么久的声明.
while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
..
..
}
Run Code Online (Sandbox Code Playgroud)
我在网上看到,来自while循环的条件是最右边的[!feof(stdin)].然后,使用上面的while语句而不是什么
while(!feof(stdin))
{
printf("> ");
fgets(str, 100, stdin);
...
...
}
Run Code Online (Sandbox Code Playgroud)
另外,while语句是一个表达式,1,1是一个有效的表达式吗?