c++ - 为什么在 C++ 中允许多个预增量但在 C 中不允许?

标签 c++ c language-lawyer

为什么

int main()
{
    int i = 0;
    ++++i;
}

有效的 C++ 但无效的 C?

最佳答案

C 和 C++ 对前缀++ 的结果有不同的说法。在 C++ 中:

[expr.pre.incr]

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 中:

6.5.3 Unary operators

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/

相关文章:

c - I2C读取时出现奇怪的延迟问题

c++11 decltype(e) 是e命名的实体的类型

c - 为什么一致性实现的行为会有所不同 w.r.t.具有内部链接的不完整数组类型?

c++ - 与 perror 等效的 C++ 流是什么?

c++ - C++继承中成员函数的访问

c++ - "Overriding"ostream& 运算符<<

c++ - 如何从两个 vector (实数和虚数)中获取复数 vector

c - 重定向标准输出,不理解行为

c - 如何将C中的框居中?

c++ - 为什么 std::unique_ptr operator* 会抛出而 operator-> 不会抛出?