Sunday, July 09, 2006

Lvalues and rvalues

Lvalues and rvalues

Have you found this error? non-lvalue in assignment
or any error involved with lvalues.

What are lvalues?
Lvalues are references to objects that appear to left side of assignment statements. This definition may be not accurate as const objects are lvalues although they cannot appear on the left side of an assignment statement. So, this definition can be modified to “references to objects”. So this objects must have memory locations or lvalues have addresses.

While rvalues:
Expressions that can appear on right side of assignment statements. Rvalues cannot appear on left side of assignment statements.

Lvalues and rvalues:
Lvalues can appear in a place that requires rvalues. Lvalues are converted to rvalues. Rvalues cannot be converted to lvalues. Therefore, it is possible to use every lvalue expression as rvalue place, but not vice versa.
These operators must be applied to lvalues:
1. &
2. ++ --
3. = += -= *= %= <<= >>= &= ^= |=

Examples of lvalues and rvalues:
1. x = 5; // x is an lvalue; 5 is an rvalue
2. array[10] = 3 // array[10] is an lvalue while 3 is an rvalue
3. X = Y + 5 ; // X is an lvalue Y + 5 is an rvalue
4. A function that returns a reference is an lvalue else is an rvalue expression.
5. *ptr = 10 // *ptr is an lvalue; 10 is an rvalue
6. x = y ; // x is an lvalue y is an lvalue converted to rvalue.
7. Casts are lvalues.

Enumerations and const data:
Both const data and enumerations can't appear at left side of assignment statements. Enumerations aren't lvalues while const data are lvalues. Enumerations doesn't have addresses. The are translated at compilation time to there numeric values. While static members are constructed at runtime.

class Class1{
Class1( int x=100 ):MAX(x){}

const int MAX ;

Here MAX is initialized with x. MAX is const and have an address. Every instance of Class1 have a const data MAX and every instance may have different value. You may use static const data if it's common among all instances.

class Class2{


enum { MAX=100 } ;


You may notice that enum can't be static because they aren't lvalues or they aren't constructed at run-time.

y+5 = 10 generated the top error.
Because y+5 is an rvalue placed in an lvalue place.

A final notice is #define statements are different from enumerations and const data as they are macros and substituted in a pre-compilation process.


Anonymous said...

I found this site using [url=][/url] And i want to thank you for your work. You have done really very good site. Great work, great site! Thank you!

Sorry for offtopic

Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!