开发者

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 开发者_StackOverflow中文版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;
}


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.]


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜