为什么
int main()
{
int i = 0;
++++i;
}
有效的 C++ 但无效的 C?
最佳答案
C 和 C++ 对前缀++ 的结果有不同的说法。在 C++ 中:
The operand of prefix ++ is modified by adding 1. The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, 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. The expression ++x is equivalent to x+=1.
所以++ 可以再次应用于结果,因为结果基本上只是被递增的对象并且是一个左值。然而,在 C 中:
The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.
The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.
结果不是左值;这只是增量的纯值。所以你不能应用任何需要左值的运算符,包括++。
如果您曾经被告知 C++ 和 C 是彼此的超集或子集,请知道事实并非如此。有许多不同之处使该断言为假。
关于c++ - 为什么在 C++ 中允许多个预增量但在 C 中不允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48203314/