逗号运算符如何在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) 如果你看到这段代码,
class A{
public:
A(int a):var(a){}
int var;
};
int f(A obj) {
return obj.var;
}
int main() {
//std::cout<<f(23); // output: 23
std::cout<<f(23, 23); // error: too many arguments to function 'int f(A)'
return 0;
}
Run Code Online (Sandbox Code Playgroud)
f(23, 23) 不编译,因为逗号在此处充当分隔符而不是逗号运算符.
所有逗号都不能用作逗号运算符?或者相反?
当我查看库代码时,我发现了以下行
int number = config.nodes,i,fanout=numP/2;
Run Code Online (Sandbox Code Playgroud)
我假设config是指向某个东西的指针,但声明中是否有逗号?并做那样的任务?