Two variables
int x, y;
are going to be compared and the greater of them is going to be assigned to another variable,
int greatest;
The first thing that comes to mind is
if (x > y) { greatest = x; }
else { greatest = y; }
Is there any other way that is much more efficient and clever?
The standard header <algorithm>
provides the standard function std::max
. One of the overloads for this function compares two objects and returns a reference to the largest of the two. In your case, the expression would be :
auto greatest = std::max(x, y)
If there is a "most efficient" way to get the largest of the two you, you should rely on the underlying implementation to use it for you. std::max
should implement the best way of doing it. But even if you are using a weak standard library implementation that doesn't, the compiler should still catch this and optimize it.
Remember that in c++ your code describes a behavior. It is not a list of instructions that the compiler will execute verbatim. Your code will be transformed by the compiler to implement these micro optimizations for you where they are known to exist.