为什么下面的代码不会产生编译错误?
我正在使用 VS2005 编译器,我希望以下代码给出编译错误。
int a=1, b= 2, c=3;
a = (b,c);
赋值后的值为 3。根据我的理解,它应该给出编译错误。
我很高兴知道这背后是否有任何正当理由。
I am using VS2005 compiler and I am expecting following code to give compilation error.
int a=1, b= 2, c=3;
a = (b,c);
value of a after assignment is 3. As per my understanding it should give compilation error.
I would be happy to know if there is any valid reason behind this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的代码中唯一的错误是您忘记了第二行末尾的分号,但我认为这是撰写问题时的印刷错误,而不是问题的实际主旨。
我认为您所显示的代码没有理由产生编译错误。它对我来说编译得很好,事实上,
a
的值是 3。参见你自己:下面的代码返回 3:
诀窍是你使用 逗号运算符,它评估其第一个操作数并然后丢弃结果,然后计算第二个操作数并返回其值。
但是,正如 Charles Bailey 指出的那样,您必须将问题中显示的代码包装在函数内,否则您将得到任何编译器中的编译错误。 C++ 不允许在函数之外使用赋值语句。
The only error in your code is that you forgot the semicolon at the end of the second line, but I assume that was a typographical error in composing your question, rather than the actual thrust of your question.
I see no reason why the code you've shown should produce a compilation error. It compiles just fine for me, and the value of
a
is, in fact, 3.See for yourself: the following code returns 3:
The trick is your use of the comma operator, which evaluates its first operand and then discards the result, and then evaluates the second operand and returns its value.
However, as Charles Bailey notes, you have to wrap the code shown in the question inside of a function, otherwise you will get compilation errors in any compiler. C++ doesn't allow assignment statements outside of functions.
您在 C++ 中使用逗号运算符,它并不常用。其工作原理如下:
它评估
并丢弃结果,然后评估
并将返回的结果作为整个表达式的值。You are using the comma operator in C++, it is not commonly used. This works as follows
It evaluates
<expression1>
and discards the results and then evaluates<expression2>
and takes the result of that is returned as the value of the whole expression.这段代码没有错误。为什么你认为应该有编译错误?这里只是一个 逗号运算符,它评估其所有参数,但返回最右边的一个:在本例中为 3。
There is no error in this piece of code. Why do you think there should be a compilation error? All here is is a comma operator which evaluates all its parameters, but returns the rightmost one: in this case 3.
引用http://en.wikipedia.org/wiki/Comma_operator:
To quote http://en.wikipedia.org/wiki/Comma_operator:
我刚刚在 VS2005 上对此进行了测试,并且按照预期得到了编译错误。
声明行很好,但正如预期的那样,赋值语句在函数外部无效。编译器似乎将其解释为尝试使用默认的
int
类型重新初始化a
,这两种类型都不合法。I've just tested this on VS2005 and I get compilation errors as expected.
The declaration line is fine, but as expected the assignment statement is not valid outside of a function. The compiler appears to interpret it as an attempt to re-initialize
a
with a defaultint
type, neither of which is legal.