为什么多个减量运算符在C ++中工作时为什么不在C中工作? [英] Why don't multiple decrement operators work in C when they work in C++?

查看:106
本文介绍了为什么多个减量运算符在C ++中工作时为什么不在C中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看问题并尝试一些代码:

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

int x = 100;

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

我尝试使用gcc进行编译,并出现以下错误:

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 )

但是使用g++进行编译是可行的.为什么此代码在C ++中有效,但在C中无效?

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

推荐答案

在C中,--x是一个值,而不是一个左值.其作用是减小x,并求值为新分配的x值.由于--x不是左值,因此不能递减.

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.

在C ++中,--x是一个左值,而不是一个右值.它的作用是递减x,并作为左值评估为x.由于--x还是左值,因此可以再次递减.

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.

在C ++中将--x用作左值有意义的原因是因为C ++引入了引用类型.给定

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;

调用f(--i)可能有意义,它会在递减后通过引用传递i.

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

由于C没有引用类型,所以--i中的左值没有什么意义.从历史上看,从来没有,并且与C ++不同,C从来没有获得改变规则的令人信服的理由.

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.

请注意,与使--x成为使它实际工作的左值相比,C ++需要更广泛的更改.将--x设置为左值时,将没有任何其他行为,这将使--x无法定义,因为对x的修改和后续的左值到值的转换之间没有序列点.对于----x来说更清楚. C ++必须修改排序规则才能使其正常工作.在C语言中,对排序规则的修改可能会导致现有编译器无法遵守新规则,因此除非有很大的好处,否则此类修改可能会被拒绝.

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.

这篇关于为什么多个减量运算符在C ++中工作时为什么不在C中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆