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

╄→尐↘猪︶ㄣ 提交于 2019-12-03 05:29:59

问题


Looking at this question and trying out some of the code:

int x = 100;

while ( 0 <-------------------- x )
{
    printf("%d ", x);
}

I attempted to compile with gcc and got the following error:

file.c: In function 'main':
file:c:10:27: error: lvalue required as decrement operand
 while ( 0 <-------------------- x )

But compiling with g++ works. Why is this code valid in C++ but not C?


回答1:


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.



来源:https://stackoverflow.com/questions/42355908/why-dont-multiple-decrement-operators-work-in-c-when-they-work-in-c

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