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

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?

有帮助吗?

解决方案

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.

bIsFALSE is false because (true, false) evaluates true, ignores the result, then evaluates and yields false.

bIsAlsoTRUE is true because ((true, false), true) evaluates (true, false), ignores the result, then evaluates and yields true.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top