Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 762
Adisak Avatar asked May 04 '11 00:05

Adisak


1 Answers

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.

like image 112
James McNellis Avatar answered Oct 12 '22 17:10

James McNellis