difference between lvalue and rvalue

Suppose we have the example code shown below in C. Will it compile? How do the concepts of lvalues and rvalues work in this problem?

 
#define X 8
int main(void)
{
	++X; // will this line compile?
        return 0;

}

The concept of lvalues and rvalues must be explained a bit in order to really understand the code above, and the problem being asked. Before we proceed, you should note that the definition of lvalues and rvalues presented here is not exact as even the C Standards themselves are rather vague on the definition.

The difference between rvalues and lvalues

An object is a region of memory that can be examined, but not necessarily modified. An lvalue is an expression that refers to such an object. The term lvalue originally referred to objects that appear on the left (hence the ‘l’) hand side of an expression. That definition no longer applies since any const-qualified type is also considered to be an lvalue, but it can never appear on the left hand side of an assignment statement because it can not be modified. So, the term "modifiable lvalue" was created to refer to an lvalue that can be modified, and a const-qualified type does not fall into this category.

An rvalue is any expression that has a value, but cannot have a value assigned to it. One could also say that an rvalue is any expression that is not an lvalue . An example of an rvalue would be a literal constant – something like ’8′, or ’3.14′. So, clearly the value ’8′ in the code above is an rvalue.

Now let’s try to solve the problem. Strictly speaking, the operand of the prefix (or postfix) increment operator must be a modifiable lvalue. So, what is the operand of the prefix increment operator in our code above?

Since X is a macro, the statement above will expand to “++8″ after the preprocessor is run. This means “8″ is the operand of the prefix increment operator. And, because 8 is an rvalue it can not be used as an argument to “++”. This, in turn, means that the code above will not compile.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值