Sriram Subramanian
Sriram Subramanian

Reputation: 2753

Why this code compiles in VS? ("extra" comma)

The line below is inside a for loop. If the method fails, it needs to break. CATEGORY_1 is an enum. I added this enum as a new parameter to AddToList method with a default value. If you see closely below, I actually made the mistake of putting the comma and the enum outside the parameter list of the function. This compiles perfectly fine with VS2010. So I had a hard time finding that that the default value was being passed for that parameter instead of CATEGORY_1. Does anyone know why this succeeds?

if (! AddToList(obj1, (unsigned int) Val), CATEGORY_1)
{
    break;
}

Upvotes: 2

Views: 119

Answers (2)

ildjarn
ildjarn

Reputation: 62975

The comma operator will simply discard the result of the first expression and evaluate the value of the second expression. So in this case, if bool(CATEGORY_1) == true then the if would never evaluate; conversely, if bool(CATEGORY_1) == false then the if would always evaluate. In neither case would it matter what AddToList returned.

Upvotes: 1

James McNellis
James McNellis

Reputation: 355107

In C++, the comma isn't just a separator; it can also be an operator. That comma is an operator. The comma operator evaluates the first expression, discards the result, then evaluates the second expression and yields its result.

!AddToList(obj1, (unsigned int) Val) , CATEGORY_1
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^
First expression                       Second expression

[Of course, the comma operator, like most other operators, can be overloaded, and if an overload is used here, the semantics could be different. This is the behavior of the built-in comma operator.]

Upvotes: 7

Related Questions