سؤال

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