Sir Visto
Sir Visto

Reputation: 703

Could a compiler optimisaton give an lvalue rather than rvalue?

The following code:

int x = 0;
x+0 = 10;

unsurprisingly produces the compiler error

lvalue required as left operand of assignment

However, is it guaranteed that all standards-conforming compilers will produce a similar error, or could a compiler legitimately treat line 2 as

x = 10;

which then would compile?

Upvotes: 2

Views: 60

Answers (2)

Chris Beck
Chris Beck

Reputation: 16204

Yes, compilers must reject this.

A good description of value categories can be found here: https://medium.com/@barryrevzin/value-categories-in-c-17-f56ae54bccbe

One of the takeaways is, the value category of an expression can be determined by looking at the type decltype ((expr)).

Compiler optimations do not change the types of expressions, and they generally happen after name resolution, determination of types, overload resolution etc.

Gcc is known to perform some constant folding in the front end but i would be shocked if any version of gcc compiles your example.

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50053

Yes, it is guaranteed you get an error (or more precisely, some diagnostic). Compiler optimization never makes ill-formed code well formed.

Upvotes: 5

Related Questions