Re: returning lvalue in C vs C++



* Ben C:
Can anyone explain this:

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;
}

$ gcc -x c++ main.c

no problems in C++, but

$ gcc -x c main.c

main.c: In function ‘main’:
main.c:17: error: invalid lvalue

I'm using gcc version 4.0.2 20050901.

It's invalid in C++ too.

Comeau Online reports:

Comeau C/C++ 4.3.3 (Aug 6 2003 15:13:37) for ONLINE_EVALUATION_BETA1
Copyright 1988-2003 Comeau Computing. All rights reserved.
MODE:strict errors C++

"ComeauTest.c", line 22: error: expression must be a modifiable lvalue
f().x = 200; /* "invalid lvalue" in C, but not in C++
apparently */
^

1 error detected in the compilation of "ComeauTest.c".

However, the 1998 standard isn't very clear. §5.2.5/4 second hyphen tells us that in the expression E1.E2, "If E1 is an lvalue, then E1.E2 is an lvalue.". But nothing is said of the case where E1 is not an lvalue. One must simply /infer/ that when E1 is not an lvalue, E1.E2 is not an lvalue, either. I don't think was clarified in 2003.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
.



Relevant Pages