Are literal strings and function return values lvalues or rvalues?
Just wonder if a literal string is an lvalue or an rvalue. Are other literals (like int, float, char etc) lvalue or rvalue?
Is the return value of a function an lvalue or rvalue?
How do you tell the difference?
Solution 1:
- string literals are lvalues, but you can't change them
- rvalue, but if it's a pointer and non-NULL, the object it points to is an lvalue
The C standard recognizes the original terms stood for left and right as in L = R
; however, it says to think of lvalue as locator value, which roughly means you can get the address of an object and therefore that object has a location. (See 6.3.2.1 in C99.)
By the same token, the standard has abandoned the term rvalue, and just uses "the value of an expression", which is practically everything, including literals such as ints, chars, floats, etc. Additionally, anything you can do with an rvalue can be done with an lvalue too, so you can think of all lvalues as being rvalues.
Solution 2:
There are two kinds of expressions in C: 1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment. 2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment. Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and cannot appear on the left-hand side. Following is a valid statement: int g = 20; But following is not a valid statement and would generate compile-time error: 10=20;
Solution 3:
there's a definition for C++ from Microsoft. By this definition, a literal string, say "hello world", is lvalue, because it's const and not temporary. Actually it persists across your application's lifetime.