0
int x = 8;
int y = x ;

Here how a lvalue can be act as rvalue ? I know this is a silly question , but i just want to make my concepts clear on rvalue and lvalue .

Viku
  • 2,845
  • 4
  • 35
  • 63

2 Answers2

3

Through an lvalue to rvalue conversion.

You can use an lvalue almost anywhere where an rvalue is required and an implicit lvalue to rvalue conversion will occur automatically.

Informally this conversion is "evaluating" or "taking the value of" the object that the lvalue refers to. This isn't strictly true in all cases; in unevaluated contexts, such as the operand of sizeof, the value of the object won't be used.

ISO/IEC 14882:2011 4.1 [conv.lval]:

A glvalue (3.10) of a non-function, non-array type T can be converted to a prvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the prvalue is the cv-unqualified version of T. Otherwise, the type of the prvalue is T.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
2

An lvalue is any value that can appear on the left hand side of an assignment. Something that can be assigned to, like the variable x in this case. Rvalues are things that have a value, like 8 or getting the value of x. You can think of lvalues as a subset of rvalues, that is all lvalues can have their value queried and used as an rvalue.

Will
  • 4,585
  • 1
  • 26
  • 48
  • 1
    I think rvalue is a subset of lvalue .Please correct if i am wrong . – Viku Dec 24 '12 at 18:41
  • What I mean by that is that every lvalue can be used as an rvalue. This is not true the other way round. You can't assign to the number `8` for example. If we think of them as 'things you can get the value of'(rvalue) and 'things you can assign to'(lvalue) then everything you can assign to is something you can get the value of. – Will Dec 24 '12 at 18:44
  • @viku: Every expression in C++ has one of three value categories: _lvalue_, _xvalue_ or _prvalue_. The only _lvalues_ that are also _rvalues_ are _xvalues_ which are things like function call expressions for functions returning an _rvalue_ reference. (For completeness, a _glvalue_ is used to refer either an _lvalue_ or an _xvalue_ and an _rvalue_ is used to refer to an expression that is either an _xvalue_ or a _prvalue_.) – CB Bailey Dec 24 '12 at 18:52
  • @viku: The point of my last comment, which was a little unclear, was to explain why you normally need the lvalue-to-rvalue conversion to take place when you use an lvalue where an rvalue is needed. – CB Bailey Dec 24 '12 at 19:01