lvalue and rvalue

Every C++ expression is either an lvalue or an rvalue. An lvalue refers to an object that persists beyond a single expression. You can think of an lvalue as an object that has a name. All variables, including nonmodifiable (const) variables, are lvalues. An rvalue is a temporary value that does not persist beyond the expression that uses it. To better understand the difference between lvalues and rvalues, consider the following example:

// lvalues_and_rvalues1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main()
{
   int x = 3 + 4;
   cout << x << endl;
}

In this example, x is an lvalue because it persists beyond the expression that defines it. The expression3 + 4 is an rvalue because it evaluates to a temporary value that does not persist beyond the expression that defines it.

The following example demonstrates several correct and incorrect usages of lvalues and rvalues:

// lvalues_and_rvalues2.cpp
int main()
{
   int i, j, *p;

   // Correct usage: the variable i is an lvalue.
   i = 7;

   // Incorrect usage: The left operand must be an lvalue (C2106).
   7 = i; // C2106
   j * 4 = 7; // C2106

   // Correct usage: the dereferenced pointer is an lvalue.
   *p = i; 

   const int ci = 7;
   // Incorrect usage: the variable is a non-modifiable lvalue (C3892).
   ci = 9; // C3892

   // Correct usage: the conditional operator returns an lvalue.
   ((i < 3) ? i : j) = 7;
}

The examples in this topic illustrate correct and incorrect usage when operators are not overloaded. By overloading operators, you can make an expression such asj * 4 an lvalue.

====================================================

The definition of << C++ prime>>:

lvalue: An expression that yields an object or function. A nonconst lvalue that denotes an object ma be the left-hand operand of assignment.

rvalue: Expression that yields a value but not the associated location, if any, of that value.

Quoted from website:

http://msdn.microsoft.com/en-us/library/f90831hc.aspx

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值