A C++ newbie question: I found the following function:

int &min(int &x, int &y)
{ return x < y ? x : y; }

I am confused of the usage of “&”.
Is that possible to re-write the above function as

int &min(int x, int  y)
{ return x < y ? x : y; }


int  min(int &x, int & y)
{ return x < y ? x : y; }
7 Years
Discussion Span
Last Post by mike_2000_17

Well, they mean different things. They all accomplish the same basic end result, BUT whether the rewritten version(s) works properly or not depends on how the calling code is written and what type of return that code is expecting. The different argument/parameter formatting will also affect the efficiency of the function. The first revised version is less efficient than the original and the second version.

Edited by Fbody: n/a

Votes + Comments

The original means:
Return a reference to the smallest of two variables from the caller's scope.

The first revision means:
Return a reference to the smallest of two temporary variables that will go out-of-scope as soon as the function returns. (i.e. This is an ERROR! This will lead to undefined behavior! You should not return a reference to a temporary variable (there are only very specific fringe cases in which this can be done/useful, but leave that to the experts)).

The second revision means:
Return the value of the smallest of two variables from the caller's scope.

A third revision (int min(int,int)) means:
Return the value of the smallest of two values passed to the function.

As for efficiency, well, they are fundamentally different functions, so it doesn't really compare. Between the second and third revisions (which accomplish exactly the same), the third one is a tiny bit more likely to be more efficient (avoids a level of indirection, in theory), however, in practice, it is almost certain that there will be no difference. The same goes for the original, which can be used in place of the second or third revisions (in theory it is slightly worse than the revisions, but in practice it's the same). But the original serves a purpose that no other version can serve, so, if that specific functionality is needed, it is the only option.

N.B.: the reason for this ordering of efficiency is only because it is a native primitive type (int), if it were a more complex class, then the efficiency order would be reversed: original would be the best, the second revision the second best, and the third revision the worse.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.