简体   繁体   English

有人可以解释这个 C++ 逗号运算符短路示例吗?

[英]Can someone explain this C++ comma operator short-circuiting example?

Can someone explain this C++ comma operator short-circuiting example?有人可以解释这个 C++ 逗号运算符短路示例吗?

bIsTRUE     = true, false, true;
bIsFALSE    = (true, false), true;
bIsAlsoTRUE = ((true, false), true);

Why does the second version short-circuit and return false (at least in MSVC++) and the other two versions do not but return true ?为什么第二个版本短路并返回false (至少在 MSVC++ 中)而其他两个版本没有但返回true

The comma operator has lower precedence than assignment, so these are parsed as逗号运算符的优先级低于赋值,因此这些被解析为

(bIsTRUE     = true), false, true;     
(bIsFALSE    = (true, false)), true;   
(bIsAlsoTRUE = ((true, false), true)); 

The comma operator does not short-circuit.逗号运算符不会短路。 It evaluates its left operand, ignores the result, then evaluates its right operand.它计算左操作数,忽略结果,然后计算右操作数。

bIsTRUE is true because the right operand of the assignment is true . bIsTRUEtrue ,因为赋值的右操作数为true

bIsFALSE is false because (true, false) evaluates true , ignores the result, then evaluates and yields false . bIsFALSEfalse ,因为(true, false)评估true ,忽略结果,然后评估并产生false

bIsAlsoTRUE is true because ((true, false), true) evaluates (true, false) , ignores the result, then evaluates and yields true . bIsAlsoTRUEtrue ,因为((true, false), true)评估(true, false) ,忽略结果,然后评估并产生true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM