请教一个关于C++表达式的问题
int a = 2;
(a++) += a;
(++a) += a;
为什么前一个表达式编译错误,有人说a++是个右值不能放在等号的左边,可是下面的表达式++a也是个右值啊,为什么就可以顺利编译呢?这是语法上的问题还是编译器的问题,还有朋友说,是a++ 优先级低,编译器无法确定 a的值所以编译错误,可是最终还是没有明确答案,求高手解释
[解决办法]
另外
(++a) += a;
结果是不确定的
[解决办法]
在c++中,a++返回的是个const int,这是一个临时对象,只能作为右值;++a返回的是int &,是a的引用,当然可以作为左值。
在c中,两者返回均为右值,所以(a++)+=a;这个在gcc下调试会有错。
[解决办法]
对于内建++,++a在C++中是左值,在C中不是。
当然就算编译过也有未定义行为。
ISO C++11
5.3.2 Increment and decrement [expr.pre.incr]
1 The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. If x is not of type bool, the expression ++x is equivalent to x+=1 [ Note: See the
discussions of addition (5.7) and assignment operators (5.17) for information on conversions. —end note ]
ISO C11(N1570)
6.5.3.1
2 The value of the operand of the prefix ++ operator is incremented. The result is the new
value of the operand after incrementation. The expression ++E is equivalent to (E+=1).
See the discussions of additive operators and compound assignment for information on constraints, types, side effects, and conversions and the effects of operations on pointers.
注意和C++不同,C语言中value就是通常所说的rvalue。很明显value不是lvalue:
6.3.2.1/1
...
64) The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an object ‘‘locator value’’. What is sometimes called ‘‘rvalue’’ is in this International Standard described as the ‘‘value of an expression’’.
请问一个关于C++表达式的有关问题
请教一个关于C++表达式的问题int a 2(a++) + a(++a) + a为什么前一个表达式编译错误,有人说a++是个
