paulm
paulm

Reputation: 5882

C++ comma operator confusion

Similar question to:

How is the comma operator being used here?

BOOL bShowLoadingIcon = FALSE;
if (sCurrentLevelId_5C3030 == 0 || sCurrentLevelId_5C3030 == 16 || (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1))
{
    bShowLoadingIcon = FALSE;
}

In the above code sample what values/range of sCurrentLevelId_5C3030 would cause bShowLoadingIcon to be set to TRUE. Is it possible it would be set to TRUE and also become true (overall if expression) thus also then being set back to FALSE?

I have no idea what (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1) is actually doing.

Upvotes: 0

Views: 108

Answers (2)

Soham
Soham

Reputation: 826

In C++, the comma operator (statementX, statementY) first executes statementX, and then statementY. The expression holds the value of the second statement.

In your code, bShowLoadingIcon is assigned the value TRUE, and then the value that C++ checks for in the if statement is whether sCurrentLevelId_5C3030 == -1.

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182743

C++ only evaluates a boolean OR if it needs to. So if sCurrentLevelId_5C30303 is 0 or 16, the last statement never gets evaluated.

If (bShowLoadingIcon = TRUE, sCurrentLevelId_5C3030 == -1) does get evaluated, it first sets bShowLoadingIcon to TRUE and then evaluates to the result of sCurrentLevelId_5C3030 == -1. If that's true, then bShowLoadingIcon will just get set back to FALSE.

So in summary, bShowLoadingIcon is set to FALSE. Then if sCurrentLevelId_5C3030 is neither 0 nor 16, then bShowLoadingIcon is set to TRUE, only to be set back to false if sCurrentLevelId_5C3030 is -1.

So, in even more summary, bShowLoadingIcon is set to TRUE if sCurrentLevelId_5C3030 is neither 0 nor 16 and stays that way so long as sCurrentLevelId_5C303030 is not -1.

It's equivalent to:

BOOL bShowLoadingIcon = (
    (sCurrentLevelId_5C3030 != 0) &&
    (sCurrentLevelId_5C3030 != 16) &&
    (sCurrentLevelId_5C3030 != -1)) ? TRUE : FALSE:

Or, if you prefer:

BOOL bShowLoadingIcon = (
    (sCurrentLevelId_5C3030 == 0) ||
    (sCurrentLevelId_5C3030 == 16) ||
    (sCurrentLevelId_5C3030 == -1)) ? FALSE : TRUE;

Upvotes: 4

Related Questions