Michael Ulm
Michael Ulm

Reputation: 802

Only one evaluation guaranteed for std::min/std::max

Does the C++ standard guarantee that the call

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

evaluates the functions f and g only once?

Upvotes: 5

Views: 540

Answers (1)

Benoît
Benoît

Reputation: 16994

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)

Upvotes: 13

Related Questions