Not all lvalues can be on the l.h.s. of an assignment

Hi everyone,

I'm trying to go a understand a bit deeper the concept of lvalue, xvalue,glvalue,rvalue,prvalue from "The C++ Programming Language, 4th edition".

It's written: "However, not every lvalue may be used on the left-hand side of an assignment; an lvalue can refer to a constant (ยง7.7)"

For the sentence after ";" indeed, kooking at 7.7, we see that we can write

const double& cdr{1};


But what is an example of an lvalue that can't be used on the l.h.s. of an assignment?

Looking at https://en.cppreference.com/w/cpp/language/value_category, I see that also strings literals such as "Hello, World!" and a cast expression to lvalue reference type, such as static_cast<int&>(x) are lvalues references and clearly they cannot be on the l.h.s. of an assignment. Is this what Stroustrup had in mind?
Last edited on
But what is an example of an lvalue that can't be used on the l.h.s. of an assignment?
'cdr' is. cdr = 0 is an invalid expression.

a cast expression to lvalue reference type, such as static_cast<int&>(x) are lvalues references and clearly they cannot be on the l.h.s. of an assignment.
No. If the compiler accepts the cast as valid, static_cast<int &>(x) can be on the LHS of an assignment. Why couldn't it be?
Last edited on
cdr = 0 is an invalid expression.


Ah yes, thanks.


If the compiler accepts the cast as valid, static_cast<int &>(x) can be on the LHS of an assignment. Why couldn't it be?


I never tried this but yes, it makes sense and I just tried it.

For what concerns string literals, also "Hello, World!" cannot be on the l.h.s. of an assignment, and I'd like to have a check about this now:

It is an lvalue, because in practice its type is const char *, i.e. a const array of characters, but since it's const we can't modify it.
Indeed, if I write "Hello, World"=" "; I have the compiler error: error: read-only variable is not assignable

Is my argument correct?
That's the immediate reason, yes, but the ultimate reason is that being able to assign to a literal would raise the question of what happens to subsequent uses of that literal.
1
2
3
4
5
std::string s = "hello";
"hello" = "goodbye";
if (s == "hello"){
    //Do we enter here or not?
}
Thanks @helios

Indeed that if clause would lead to some troubles... for insrance, if s=="hello" were true, then it's like if "hello"=="goodbye" is true, which wouble be really weird...
Topic archived. No new replies allowed.