I recently saw the following in the codebase:
我最近在代码库中看到了以下内容:
bool bRes = (a < b) ? a=b, true : false;
If a < b
, then a=b
is executed and bRes
is true. What exactly is going on here? The docs for conditional operator don't mention anything about chaining expressions.
如果a < b,则执行a=b, bRes为真。这里到底发生了什么?条件运算符文档中没有提到任何有关链接表达式的内容。
edit: to be clear I get the conditional operator part, it's the a=b, true
as a single expression that confused me.
编辑:很明显,我得到了条件运算符部分,它是a=b,这是一个令我困惑的表达式。
2 个解决方案
#1
11
Eww. That is a usage of the comma operator. a=b, true
does precisely what you said. It executes each expression and results in the value of the last expression.
恶。这是逗号运算符的用法。a=b,你说的没错。它执行每个表达式并产生最后一个表达式的值。
#2
4
That is a correct code, but written in a strange style. The language allows to use the comma operator this way.
这是一个正确的代码,但是以一种奇怪的风格编写。该语言允许以这种方式使用逗号运算符。
The equivalent is
相当于是
bool bRes;
if (a < b)
{
a = b;
bRes = true;
}
else
bRes = false;
#1
11
Eww. That is a usage of the comma operator. a=b, true
does precisely what you said. It executes each expression and results in the value of the last expression.
恶。这是逗号运算符的用法。a=b,你说的没错。它执行每个表达式并产生最后一个表达式的值。
#2
4
That is a correct code, but written in a strange style. The language allows to use the comma operator this way.
这是一个正确的代码,但是以一种奇怪的风格编写。该语言允许以这种方式使用逗号运算符。
The equivalent is
相当于是
bool bRes;
if (a < b)
{
a = b;
bRes = true;
}
else
bRes = false;