逗号运算符如何在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) 你看到它用于for循环语句,但它在任何地方都是合法的语法.您在其他地方找到了什么用途,如果有的话?
所以我在某个地方遇到了这个问题:
情况1:
int a;
a = 1, 2, 3;
printf("%d", a);
Run Code Online (Sandbox Code Playgroud)
案例2:
int a = 1, 2, 3;
printf("%d", a);
Run Code Online (Sandbox Code Playgroud)
解释说:
第二种情况给出错误,因为逗号用作分隔符,在第一种情况下=优先于,它,所以它基本上是(a=1), 2, 3;
但我想问为什么在案例2 中=没有优先权,?
非常简单的程序,不知道为什么它不起作用:
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
int main ()
{
ofstream myfile ("test.txt");
if (myfile.is_open())
{
for( int i = 1; i < 65535; i++ )
{
myfile << ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i );
}
myfile.close();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
基本上它应该打印该句子65535次,然后将其保存为txt文件.但是txt文件只有一个从1到65535的数字列表,没有单词或格式.有任何想法吗?感谢帮助.
类似的问题:
BOOL bShowLoadingIcon = FALSE;
if (sCurrentLevelId_5C3030 == 0 || sCurrentLevelId_5C3030 == 16 || (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1))
{
bShowLoadingIcon = FALSE;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码示例中,sCurrentLevelId_5C3030的值/范围将导致bShowLoadingIcon设置为TRUE.它是否有可能被设置为TRUE并且也变为真(如果表达式整体)因此也被设置为FALSE?
我不知道(bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1)实际上在做什么.