在阅读有关未定义行为和序列点的答案后,我写了一个小程序:
#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:警告:逗号表达式的左侧操作数无效
Run Code Online (Sandbox Code Playgroud)[-Wunused-value] i = (i, ++i, 1) + 1; ^
为什么?但可能会通过我的第一个问题的答案自动回答.
逗号运算符如何在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循环语句,但它在任何地方都是合法的语法.您在其他地方找到了什么用途,如果有的话?
我想在for
-loop条件中增加两个变量而不是一个.
所以类似于:
for (int i = 0; i != 5; ++i and ++j)
do_something(i, j);
Run Code Online (Sandbox Code Playgroud)
这是什么语法?
如果我使用:
1.09 * 1; // returns "1.09"
Run Code Online (Sandbox Code Playgroud)
但如果我使用:
1,09 * 1; // returns "9"
Run Code Online (Sandbox Code Playgroud)
我知道1,09不是一个数字.
逗号在最后一段代码中做了什么?
if (0,9) alert("ok"); // alert
if (9,0) alert("ok"); // don't alert
Run Code Online (Sandbox Code Playgroud)
alert(1); alert(2); alert(3); // 3 alerts
alert(1), alert(2), alert(3); // 3 alerts too
Run Code Online (Sandbox Code Playgroud)
alert("2",
foo = function (param) {
alert(param)
},
foo('1')
)
foo('3'); // alerts 1, 2 and 3
Run Code Online (Sandbox Code Playgroud) 这个(注意逗号运算符):
#include <iostream>
int main() {
int x;
x = 2, 3;
std::cout << x << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出2.
但是,如果您使用return
逗号运算符,则:
#include <iostream>
int f() { return 2, 3; }
int main() {
int x;
x = f();
std::cout << x << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出3.
为什么逗号运算符的行为与return
?
c++ return operator-precedence comma-operator language-lawyer
我已经用C和C++编程了几年,现在我刚刚开始学习大学课程而且我们的书有一个这样的函数作为一个例子:
int foo(){
int x=0;
int y=20;
return x,y; //y is always returned
}
Run Code Online (Sandbox Code Playgroud)
我从未见过这样的语法.事实上,我从未见过在,
参数列表之外使用的运算符.如果y
总是返回,那么重点是什么?是否有需要像这样创建return语句的情况?
(另外,我也标记了C,因为它适用于两者,尽管我的书特别是C++)
我可以编写代码if(1) x++, y++;
而不是if(1) {x++; y++;}
,但在某些情况下它不起作用(见下文).如果你告诉我这件事会很好.
int x = 5, y = 10;
if (x == 5) x++, y++; // It works
if (x == 5) x++, return 0; // It shows an error
Run Code Online (Sandbox Code Playgroud)
这同样适用于for
循环:
for (int i = 0; i < 1; i++) y++, y += 5; // It works
for (int i = 0; i < 1; i++) y++, break; // Does not work
Run Code Online (Sandbox Code Playgroud) comma-operator ×10
c++ ×6
c ×5
javascript ×2
operators ×2
comma ×1
expression ×1
for-loop ×1
return ×1
return-value ×1
syntax ×1