tags:

views:

87

answers:

1

Does the C++ standard guarantee that the call

c = std::min(f(x), g(x));

evaluates the functions f and g only once?

+11  A: 

Yes. Since std::min is a function, f(x) and g(x) will be evaluated only once. And returned values won't be copied. See the prototype of the function :

template<typename T>     
const T& min ( const T& a, const T& b );

It is a clear difference with preprocessor-genuinely-defined min macro :

#define MIN(A,B) ((A)<(B))?(A):(B)
Benoît
hmm... Is it possible to pull off a #define version of min AND make sure it calls each function once? Just curious...
Alexander Rafferty
For completeness' sake: you cannot however assume the order in which the methods will be evaluated, it's unspecified. For example, `gcc` usually evaluates the arguments from right to left.
Matthieu M.
@Alexander Rafferty: If it were possible it probably would have been done already in existing MIN implementations. Double evaluation of MIN parameters has been a thorn in the programmers side for a few decades.
Constantin
@Alexander: #define version of min/max, evaluating its params once is possible, but it still would contain the problem of potentially comparing incompatible data types. Linux has GCC-specific implementation of [type-safe define for min/max](http://lxr.free-electrons.com/source/include/linux/kernel.h#L622).
Dummy00001