为什么这段代码可以在VS中编译? (“额外”逗号)
下面的行位于 for 循环内。如果该方法失败,则需要中断。 CATEGORY_1 是一个枚举。我将此枚举作为新参数添加到具有默认值的 AddToList 方法。如果您仔细观察下面的内容,我实际上犯了一个错误,将逗号和枚举放在函数的参数列表之外。这在 VS2010 中编译得非常好。因此,我很难发现该参数传递的是默认值而不是 CATEGORY_1。 有谁知道为什么会成功?
if (! AddToList(obj1, (unsigned int) Val), CATEGORY_1)
{
break;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++ 中,逗号不仅是分隔符,而且是分隔符。它也可以是一个运算符。那个逗号是一个运算符。逗号运算符计算第一个表达式,丢弃结果,然后计算第二个表达式并产生其结果。
[当然,与大多数其他运算符一样,逗号运算符可以重载,如果此处使用重载,语义可能会有所不同。这是内置逗号运算符的行为。]
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.
[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.]
逗号运算符将简单地丢弃第一个表达式的结果并计算第二个表达式的值。因此,在这种情况下,如果
bool(CATEGORY_1) == true
则if
永远不会计算;相反,如果bool(CATEGORY_1) == false
则if
始终会计算。在这两种情况下,AddToList
返回的内容都无关紧要。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 theif
would never evaluate; conversely, ifbool(CATEGORY_1) == false
then theif
would always evaluate. In neither case would it matter whatAddToList
returned.