I have been reading C++ Primer for a whole day and stuck at this piece of code which I accidentally typed out:
int max = 5, min = 4;
max = (max > min) ? max : min;
It becomes so wired for me to think of it as max = max;
.
According to my understanding the right side max
becomes a rvalue so it is merely a value 5
. I'm not sure at all...
Anyone please explain it to me in plain words what's this syntax is?
As a newbie I think I'm not able to understand too complex answers.
Many thanks in advance!
There is nothing strange about the expression
max = max;
because there is no requirement the right hand side must be an rvalue, it just happens to be an rvalue often.
For example this is a typical copy from one lvalue to another
int x = 5;
int y;
y = x;
In this case x
is not an rvalue, yet it appears on the right hand side. It is simply used to copy-assign to y
.
So in your ternary expression either max = max
or max = min
are the two assignments that can possibly occur, and both are assignments using lvalues.
The expression:
max = (max > min) ? max : min;
could be decomposed to:
if (max > min) {
max = max;
} else {
max = min;
}
Thus, what is happens is max
is compared to min
and whichever is greater than the other gets assigned to max
. The last operation, in the case where max
is greater than min
, is called self assignment:
max = max;
which is a perfectly legal operation, with accordance with the standard.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.