0

Let's say I have a piece of code like this:

int y = 1;
int z = 1;
int x = std::min(y+1,z);

Looking at the documentation of std::min (here), I was wondering whether the addition in the first argument of the function creates an calculation overhead, i.e. whether y+1 is possibly executed twice.

The reason for my question is that the documentation shows this as a possible implementation of std::min:

template<class T> 
const T& min(const T& a, const T& b)
{
    return (b < a) ? b : a;
}

So does anyone know, whether y+1 is executed twice?

takahashi
  • 2,081
  • 3
  • 14
  • 24
  • "the documentation" shows that the two expressions are each only evaluated once. – Pete Becker Dec 13 '16 at 18:02
  • 8
    *"whether y+1 is possibly executed twice"*.. How is that even possible if `min` is a function, not a macro? It seems you're asking this because you've seen *"executed twice"* in case of macro, though without understanding the reason *why* that happens. Because if you understood that well, you probably would not have asked this question. If that is the case, then I'd advise you to *understand* the macro-case first. – Nawaz Dec 13 '16 at 18:02
  • 2
    [The Definitive C++ book list](http://stackoverflow.com/a/388282/2069064) – Barry Dec 13 '16 at 18:07
  • 1
    @Nawaz you are absolutely right. Thank you for pointing me to the right direction. – takahashi Dec 13 '16 at 18:18

1 Answers1

2
template<class T> 
const T& min(const T& a, const T& b)
{
    return (b < a) ? b : a;
}

It is easy to see that in this possible implementation each argument of the min function is calculated exactly once.

In your particular case temporary y + 1 is bound to the const reference a and z is bound to the const reference b. Then a and b are used to perform calculation.

From the other side macros are more dangerous in this sense.

The typical implementation of MIN macro:

#define MIN(a, b) ((a) < (b)) ? (a) : (b)

for

MIN(y + 1, z)

is preprocessed into the:

((y + 1) < (z)) ? (y + 1) : (z)

which leads to the double computation of y + 1 if y + 1 < z.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • That's a bad example, because it probably doesn't lead to a double computation in this case, only the possibility of one. A better example would be something like `MIN(printf("test"), 3);` or something with a side-effect that can't be eliminated. – David Schwartz Dec 13 '16 at 19:19
  • @DavidSchwartz I just tried to create an example which was close to the piece of code provided at the beginning of the question. Anyway, macro example is an addition to the main part of the answer. – Edgar Rokjān Dec 13 '16 at 19:24