tags:

views:

472

answers:

2
+5  Q: 

lvalue and rvalue

  1. Just wonder if a literal string is a lvalue or a rvalue. Are other literals (like for int, float, char etc) lvalue or rvalue?

  2. Is the return value of a function a lvalue or rvalue?

How do you tell the difference?

A: 

http://en.wikipedia.org/wiki/Value_(computer_science)

Patrick
I need to start posting shorter answers, you beat me by 5 seconds. :(
Roger Pate
But Roger, your asnwer wasn't just a link to wikipedia...
Pod
Perhaps Roger should have just cut and pasted the contents of the wiki article or any of the other links thrown up by google.
Patrick
+14  A: 
  1. string literals are lvalues, but you can't change them
  2. 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.

Roger Pate
Johannes Schaub - litb
It does use rvalue in the index. :P
Roger Pate
@Roger: Thanks! I just wonder about other literals other than string literal? @Johannes: I just saw function desinators are lvalues somewhre online yesterday, and remembered it was for C. Am I wrong?
Tim
Tim: I mentioned those specifically at the end, just about *everything* is an rvalue, and those literals are not lvalues.
Roger Pate
C99, 6.3.2.1/4: "A *function designator* is an expression that has function type." I believe that is saying they are rvalues, as they do not have object type. I linked to where you can find the C standard, if you're really curious, but I make no warranty on your sanity after standardese.
Roger Pate
@Roger: Thanks! I meant to ask if literals other than string literal are lvalue.
Tim
In particular, compound literals in C99 are lvalues. So you can in fact do `int *p = printf("%d", *p);`.
Johannes Schaub - litb
Hadn't thought about that before, but it makes sense in a weird way and is consistent with string literals.
Roger Pate
Johannes: what does that {} mean in your compound literal example. I tried () instead, and it is wrong because it is still rvalue not lvalue.
Tim
Tim: That's just part of the compound literal syntax. If you change it to parens, then you have `(int)(42)` which is the same as `(int)42` which is just a redundant cast, and indeed an rvalue.
Roger Pate