1

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!

5
  • max and min are merely variables. You could as well just change their names or exchange their values if you so wish. Commented Dec 29, 2015 at 13:03
  • 1
    It's kind of odd code, I would write if (min > max) max = min;. Commented Dec 29, 2015 at 13:13
  • @LightnessRacesinOrbit Actually I have been self-learning C++ for around 3 weeks, everyday started from 7 am to 11pm, only C++...LOL..I am going to take a C++ course with CS students next summer vacation. That's why I have to learn more during this holiday. Commented Dec 30, 2015 at 1:08
  • Come back after six months :) Commented Dec 30, 2015 at 1:54
  • @LightnessRacesinOrbit !!!:-) Commented Dec 30, 2015 at 2:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted! Thanks for the effort! I'm so sorry but I think I understand his answer better. Sorry!
0

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.

2 Comments

Thanks for the efforts, "is called self assignment" clearly explained my question. I will accept your answer later.
Glad that I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.