Why don't multiple decrement operators work in C when they work in C++?

白昼怎懂夜的黑 提交于 2019-12-02 17:51:21

In C, --x is a value, not an lvalue. Its effect is to decrement x, and evaluate to the newly assigned value of x. Since --x is not an lvalue, it cannot be decremented.

In C++, --x is an lvalue, not an rvalue. Its effect is to decrement x, and evaluate to x as an lvalue. Since --x is an lvalue again, it can be decremented again.

The reason why it makes sense for --x to be an lvalue in C++ is because C++ introduced reference types. Given

void f(int &);
int i;

it may make sense to call f(--i), which passes i by reference after decrementing it.

Since C doesn't have reference types, there's little point in --i being an lvalue. Historically, it never was, and unlike C++, C never gained a compelling reason to change the rules.

Note that C++ required more extensive changes than making --x an lvalue to actually let it work. Making --x an lvalue, without anything else, would make --x undefined behaviour, because there would not be a sequence point between the modification to x and the subsequent lvalue-to-value conversion. Even more clearly so for ----x. C++ had to modify the sequencing rules to make it work. In C, modifications to the sequencing rules might cause problems for existing compilers to conform to the new rules, so such modifications would likely be rejected unless there's a big benefit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!