逗号运算符如何在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循环语句,但它在任何地方都是合法的语法.您在其他地方找到了什么用途,如果有的话?
我们可以写一个if声明
if (a == 5, b == 6, ... , thisMustBeTrue)
Run Code Online (Sandbox Code Playgroud)
只有最后一个条件才能进入if身体.
为什么允许?
#include<stdio.h>
int main(void) {
int a=(1, 2), 3;
printf("%d", a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:2
任何人都可以解释输出是2吗?
我看到了这段代码:
if (cond) {
perror("an error occurred"), exit(1);
}
Run Code Online (Sandbox Code Playgroud)
为什么要这么做?为什么不呢:
if (cond) {
perror("an error occurred");
exit(1);
}
Run Code Online (Sandbox Code Playgroud) With reference to Comma-Separated return arguments in C function [duplicate] ,
x=x+2,x+1;
Run Code Online (Sandbox Code Playgroud)
will be evaluated as
x=x+2;
Run Code Online (Sandbox Code Playgroud)
However, in case of the following code
#include<stdlib.h>
#include<stdio.h>
int fun(int x)
{
return (x=x+2,x+1); //[A]
}
int main()
{
int x=5;
x=fun(x);
printf("%d",x); // Output is 8
}
Run Code Online (Sandbox Code Playgroud)
Shouldn't line [A],be evaluated as
x=x+2;
Run Code Online (Sandbox Code Playgroud)
giving x = 7
我遇到了这段代码.我通常使用'&&'或'||' 在for循环中分隔多个条件,但此代码使用逗号来执行此操作.
令人惊讶的是,如果我改变条件的顺序,输出会有所不同.
#include<stdio.h>
int main() {
int i, j=2;
for(i=0; j>=0,i<=5; i++)
{
printf("%d ", i+j);
j--;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出= 2 2 2 2 2 2
#include<stdio.h>
int main(){
int i, j=2;
for(i=0; i<=5,j>=0; i++)
{
printf("%d ", i+j);
j--;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出= 2 2 2
有人能解释一下原因吗?它似乎只检查最后一个以逗号分隔的条件.
考虑:
for (auto i = 0; i < g.size(); ++i)
for (auto j = 0; j < g.size(); ++j) if (g[i][j] == 0) dfs(g, i, j), ++regions;
return regions;
Run Code Online (Sandbox Code Playgroud)
我不喜欢一个行代码。代码在中执行if()什么?
我对“,”符号感到困惑。
通常我会这样写:
for (auto i = 0; i < g.size(); ++i)
{
for (auto j = 0; j < g.size(); ++j)
{
if (g[i][j] == 0)
{
dfs(g, i, j)
}
,++regions; // I am not sure what to do here. Inside the "if" scope??
}
}
return …Run Code Online (Sandbox Code Playgroud) 为什么在逗号运算符(例如下面的示例)中指定的表达式不被视为常量表达式?
例如,
int a = (10,20) ;
Run Code Online (Sandbox Code Playgroud)
当在全局范围内给出时产生错误"初始化器不是常量",尽管由逗号运算符分隔的两个表达式都是常量(常量表达式).为什么整个表达式不被视为常量表达式?为了澄清我已经阅读了','运算符在C中做了什么?和C逗号运算符的使用.他们没有涉及逗号运算符的这个方面.
请解释一下这个程序的输出:
int main()
{
int a,b,c,d;
a=10;
b=20;
c=a,b;
d=(a,b);
printf("\nC= %d",c);
printf("\nD= %d",d);
}
Run Code Online (Sandbox Code Playgroud)
我得到的输出是:
C= 10
D= 20
Run Code Online (Sandbox Code Playgroud)
我怀疑"运营商"在这里做了什么?
我使用代码块编译并运行程序.
c ×7
c++ ×5
comma ×3
coding-style ×1
expression ×1
for-loop ×1
if-statement ×1
return-value ×1
scope ×1