Re: returning lvalue in C vs C++



On 2006-03-30, Alf P. Steinbach <alfps@xxxxxxxx> wrote:
* Kai-Uwe Bux:
* Ben C:

struct thing
{
int x;
};

struct thing f(void)
{
struct thing ret = {100};
return ret;
}

int g(void)
{
return 10;
}

int main(void)
{
#if 0
g() = 4; /* "invalid lvalue" in C and C++ */
#endif
f().x = 200; /* "invalid lvalue" in C, but not in C++ apparently */

return 0;

I wonder if the difference is anything to do with a fundamental
difference between builtin types and user-defined types.

The values of builtin types can be represented by literals:

g() = 8;

Would assign 8 to 10. This makes no sense. I can assign 8 to a variable
of type int, but not to an _actual integer_.

There's no such thing as a "struct literal" in C or C++-- {100} is an
initializer expression, not a struct literal. I also cannot write:

return {100};

If I write:

int h(void)
{
int ret = 10;
return ret;
}

What am I returning? A copy of ret, or 10? I would say 10. But f() above
returns ret, not {100}; there is no such thing as a value of {100}.

g() returns a value, but f() returns an object. Whether you can assign
to an object or not is just a matter of whether it's const. But you can
never assign to a value. It makes sense to me to say that struct
instances are always objects, and that variables of struct types
therefore always refer to objects. Variables of builtin types refer
directly to values. This is really the difference between rvalues and
lvalues.

I sort of think based on this reasoning that f().x = 200 "should" be
allowed in both languages, and if you don't want it to happen, return a
const struct thing.

f().x is _not_ an invalid lvalue, it's a perfectly good lvalue. It looks
like the error is based on the assumption that any function return value
is an rvalue. This assumption is harmless in C because there's never any
point assigning to a return value. In C++ where you can return
references and overload operator= for user-defined types to cause
sideeffects, the compiler has to be more careful about what it does and
doesn't allow and look a bit more carefully at assignments like this.
.



Relevant Pages