- if(1, true) - 是什么意思?
我遇到了这段代码:
if (1, true) {/*...*/}
它到底意味着什么? 虽然其计算结果为 true:
void foo(){}
...
if(1, foo()) {/*...*/}
但这不会编译:
void foo(){}
...
if (1 == foo()) {/*...*/}
显然是因为编译器期望 foo() 返回一些整数值。我认为逗号会翻译为某个运算符。 if 子句中的逗号是否会在内部转换为某些内容?
I came across this code:
if (1, true) {/*...*/}
What does it actually mean?
While this evaluates to true:
void foo(){}
...
if(1, foo()) {/*...*/}
this doesnt compile:
void foo(){}
...
if (1 == foo()) {/*...*/}
obviously because compiler expects foo() to return some integral value. I thought that the comma translates to some operator.
Does that comma in the if clause translate to something internally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
逗号运算符仅计算其左操作数,然后计算其右操作数。因此,像这样的表达式
首先计算
1
,然后计算true
,从而得到表达式值true
。在这种特殊情况下,使用逗号运算符似乎毫无意义。
The comma operator simply evaluates its left operand, followed by its right operand. So an expression like
evaluates the
1
first, then thetrue
, resulting in an expression value oftrue
.In this particular case, the use of the comma operator seems rather pointless.
逗号运算符返回右操作数的结果,并丢弃左操作数的结果。
两个操作数均被求值,先左,后右。
The comma operator returns the result of the right operand, and discards the result of the left operand.
Both operands are evaluated, first left, then right.
那是逗号运算符。它先评估 1,然后评估
true
,然后检查true
是否为 true(事实确实如此),因此它执行 if。That's the comma operator. It evaluates 1, then
true
and then checks iftrue
is true, which it is, so it executes the if.正如其他人所解释的,这是逗号(或顺序求值)运算符。
但是,第二个代码片段也不起作用,请参阅 gcc 4.3.4 的输出。逗号运算符按从左到右的顺序执行其所有操作数,将每个操作数视为单个子表达式并返回链中最后一个表达式的值。由于
foo()
返回void
,因此表达式不正确。如果您的编译器接受它,则违反了语言标准。As others have explained, this is the comma (or sequential evaluation) operator.
However, the second code snippet does not work either, see gcc 4.3.4's output. The comma operator executes all its operands in left-to-right order, treating each of them as a single sub-expression and returning the value of the last expression in the chain. As
foo()
returnsvoid
, the expression is not correct. If your compiler accepts it, it is a violation of the language standard.逗号运算符。评价从左到右。结果是最右边表达式的结果。
Comma operator. Evaluation from left to right. Result is the result of the right-most expression.