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

1

12

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?

Faxon answered 4/5, 2011 at 0:38 Comment(0)
M
29

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.

Monumental answered 4/5, 2011 at 0:40 Comment(8)
Ah, a case where the added parenthesis explain all!Faxon
Just out of curiosity where would you use such functionality?Clotilda
@PeterR.: Which functionality, that comma is lower precedence than assignment? int count = 0; for (Node *p = head; p; p = p->next, ++count) {} A poor example, but for-loop increment expressions, and sometimes other similar things, can use it.Laccolith
@Fred Yup that! I actually never noticed that I used that! Thanks :)Clotilda
@Peter R.: In addition, it's possible to overload the comma operator, which is occasionally fun and useful.Monumental
Can the comma operator be overloaded for intrinsic types like "bool" or "int"? Or can you only do it with classes.Faxon
@Adisak: As with all operator overloading, at least one of the operand types must be a class or enumeration type. So, you could overload the operator for MyClass and int (to be able to use MyClass, 42) but not int and int (42, 42).Monumental
Great... I knew there was some limitation where you couldn't do it with purely intrinsic types. Thanks for clearing that up.Faxon

© 2022 - 2024 — McMap. All rights reserved.