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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With