Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

Does the C++ standard guarantee that the call

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

evaluates the functions f and g only once?

like image 204
Michael Ulm Avatar asked Sep 08 '10 07:09

Michael Ulm


People also ask

Is there a min and max function in C++?

The many variations of the min , max , and minmax functions apply to values and initializer lists. These functions need the header <algorithm> . Nearly the same holds for the functions std::move , std::forward and std::swap . You can apply them to arbitrary values.

What is std :: max in C++?

std::max is defined in the header file <algorithm> and is used to find out the largest of the number passed to it. It returns the first of them, if there are more than one.

Is std :: max Constexpr?

std::min and std::max are constexpr in C++14, which obviously means there isn't a good reason (these days) not to have them constexpr.

What does Max () do in C?

The max() function returns the greater of two values. The max() function is for C programs only. For C++ programs, use the __max() macro.


1 Answers

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)
like image 84
Benoît Avatar answered Nov 15 '22 04:11

Benoît