Whilst learning about value categories, I found that the following snippet compiled and run just fine:
#include <iostream>
int main() {
int x = 1;
int y = 2;
(true ? x : y) = 4;
std::cout << x << std::endl;
}
Here's the output:
4
First, I checked whether this statement was legal C++, and I believe it is because of the following:
N4296 5.16.4 Conditional operator [expr.cond]
If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.
Given that both x
and y
are lvalues (and therefore glvalues), the result of the conditional expression in both cases is an lvalue. On this basis, the expression seems valid. However what's not clear is whether this should have any effect.
The reason I am not sure whether the conditional statements should have an effect is because the type of the second and third operand type is int
. Even if this result int
is an lvalue, that doesn't meant it has to refer to x
or y
. It could essentially be a dummy variable, leading to no effect, and be standard conforming. In other words, I see no reason for it to resolve to an int&
rather than a separate int
.
My question is...
Is this behaviour correct and why?
I took a look at this question beforehand, but don't believe it answers my question. The answers to this question refer to an older standard, with different wording, and don't answer my question about whether the result is an int&
to x
or not.