문제

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