3 Versions of C++ max() Function:
The C++ max() function has three different versions that allow you to compare different numbers of arguments. Let's understand each version in detail.
1. max(value1, value2)
This is the basic version of the max() function, which takes two arguments & returns the larger value. It can be used with any data type that supports comparison using the `>` operator.
Example:
int maxVal = max(5, 10); // maxVal will be 10
2. max(initializer_list<T> il)
This version of the max() function takes an initializer list as an argument. An initializer list is a lightweight container that can hold a sequence of values. This version allows you to find the maximum value among multiple arguments.
Example:
int maxVal = max({5, 2, 8, 1, 9}); // maxVal will be 9
In this example, we pass an initializer list `{5, 2, 8, 1, 9}` to the max() function, & it returns the maximum value 9.
3. max(value1, value2, comp)
This version of the max() function takes three arguments: `value1`, `value2`, and a comparison function `comp`. The comparison function is used to define custom ordering criteria for determining the maximum value.
Example:
#include <algorithm>
#include <iostream>
bool compareDescending(int a, int b) {
return a > b;
}
int main() {
int maxVal = max(5, 10, compareDescending);
std::cout << "The maximum value is: " << maxVal << std::endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
The maximum value is: 5
In this example, we define a custom comparison function, `compareDescending,` that returns true if `a` is greater than `b`. We pass this function as the third argument to the max() function. As a result, the max() function uses the custom ordering defined by `compareDescending` and returns 5 as the maximum value.
Parameters of C++ max() Function:
The parameters of the C++ max() function depend on the version being used. Let's look at the parameters for each version:
1. max(value1, value2):
- `value1`: The first value to be compared.
- `value2`: The second value to be compared.
Both `value1` & `value2` should be of the same type or implicitly convertible to a common type. They can be of any data type that supports comparison using the `>` operator, such as integers, floating-point numbers, or user-defined types with overloaded comparison operators.
2. max(initializer_list<T> il):
- `il`: An initializer list containing the values to be compared.
The initializer list `il` should contain values of the same type `T`. The type `T` should support comparison using the `>` operator.
3. max(value1, value2, comp):
- `value1`: The first value to be compared.
- `value2`: The second value to be compared.
- `comp`: A comparison function object or a function pointer that defines the ordering criteria.
The `comp` parameter is a binary predicate that takes two arguments of the same type as `value1` and `value2` and returns a boolean value. It should define the custom ordering criteria for determining the maximum value. The comparison function should return `true` if the first argument is considered greater than the second argument according to the desired ordering.
Example
bool compareDescending(int a, int b) {
return a > b;
}
int maxVal = max(5, 10, compareDescending);
In this example, `compareDescending` is a comparison function that defines the ordering criteria. It returns `true` if `a` is greater than `b`, resulting in a descending order comparison.
Note: It's important to remember that the arguments passed to the max() function should be of compatible types and support the necessary comparison operations.
Return Value of C++ max() Function
The C++ max() function returns the maximum value among the arguments passed to it. The return value depends on the version of the max() function being used.
1. max(value1, value2):
- Returns the larger value between `value1` & `value2`.
- The return type is the common type of `value1` & `value2` after any necessary type conversions.
Example:
int maxVal = max(5, 10); // maxVal will be 10
double maxDouble = max(5.5, 2.3); // maxDouble will be 5.5
2. max(initializer_list<T> il):
- Returns the maximum value among the elements in the initializer list `il`.
- The return type is `T`, which is the type of the elements in the initializer list.
Example:
int maxVal = max({5, 2, 8, 1, 9}); // maxVal will be 9
double maxDouble = max({5.5, 2.3, 1.8, 4.2}); // maxDouble will be 5.5
3. max(value1, value2, comp):
- Returns the maximum value between `value1` & `value2` based on the custom ordering defined by the comparison function `comp`.
- The return type is the common type of `value1` and `value2` after any necessary type conversions.
Example
bool compareDescending(int a, int b) {
return a > b;
}
int maxVal = max(5, 10, compareDescending); // maxVal will be 5
In this example, the max() function uses the `compareDescending` function to determine the maximum value. Since `compareDescending` defines a descending order comparison, the max() function returns 5 as the maximum value.
Note: The max() function returns a copy of the maximum value. If the maximum value is a user-defined type, the copy constructor of that type will be used to create the return value.
Exceptions of C++ max() Function:
The C++ max() function does not throw any exceptions on its own. However, there are a few situations where exceptions can occur indirectly:
1. Comparison Operator Exceptions: If the types of arguments passed to the max() function do not support comparison using the `>` operator, or if the comparison operator itself throws an exception, then an exception can occur.
For example, let's say we have a user-defined type `MyClass` that does not have a proper `>` operator defined:
class MyClass {
// Class definition without a proper > operator
};
MyClass obj1, obj2;
MyClass maxObj = max(obj1, obj2); // Compilation error or runtime exception
In this case, if we try to use the max() function with objects of `MyClass`, it will result in a compilation error or a runtime exception because the `>` operator is not defined for `MyClass`.
2. Initializer List Exceptions: When using the version of max() that takes an initializer list, if the initializer list is empty, it will result in undefined behavior. The max() function expects at least one element in the initializer list.
Example:
int maxVal = max({}); // Undefined behavior
To avoid this, make sure to pass a non-empty initializer list to the max() function.
3. Comparison Function Exceptions: If the comparison function passed to the max() function throws an exception, that exception will propagate to the caller of max().
Example:
bool compareThrow(int a, int b) {
throw std::runtime_error("Comparison exception");
}
int maxVal = max(5, 10, compareThrow); // Throws an exception
In this example, the `compareThrow` function throws a runtime exception. When max() is called with `compareThrow` as the comparison function, the exception will be thrown & propagated to the caller of max().
Note: It's important to ensure that the arguments passed to the max() function have proper comparison operators defined and that any custom comparison functions used with max() are exception-safe.
How does the C++ max() Function work?
The C++ max() function works by comparing the values passed as arguments & returning the maximum value among them. Let's discuss how the max() function works internally for each version:
1. max(value1, value2):
- The max() function compares `value1` & `value2` using the `>` operator.
- If `value1` is greater than `value2`, `value1` is returned as the maximum value.
- Otherwise, `value2` is returned as the maximum value.
Internally, the max() function can be implemented in the manner given below:
template <typename T>
const T& max(const T& value1, const T& value2) {
return (value1 > value2) ? value1 : value2;
}
The max() function uses a ternary operator to compare `value1` and `value2` and returns the larger value.
2. max(initializer_list<T> il):
- The max() function iterates over the elements in the initializer list `il`.
- It keeps track of the maximum value encountered so far.
- After iterating through all the elements, it returns the maximum value.
Internally, the max() function can be implemented like below:
template <typename T>
T max(initializer_list<T> il) {
return *max_element(il.begin(), il.end());
}
The max() function uses the `max_element` algorithm from the C++ standard library to find the maximum element in the range `[il.begin(), il.end())`.
3. max(value1, value2, comp):
- The max() function compares `value1` & `value2` using the provided comparison function `comp`.
- If `comp(value1, value2)` returns `true`, `value1` is considered greater than `value2`, & `value1` is returned as the maximum value.
- Otherwise, `value2` is returned as the maximum value.
Internally, the max() function can be implemented as mentioned below:
template <typename T, typename Compare>
const T& max(const T& value1, const T& value2, Compare comp) {
return comp(value1, value2) ? value1 : value2;
}
The max() function uses the provided comparison function `comp` to determine the maximum value based on the custom ordering defined by `comp`.
Note: The max() function is a template function, which means it can work with different data types. The actual comparison and determination of the maximum value depend on the types of the arguments and the comparison operator or function used.
Uses of C++ max() Function:
The C++ max() function is a useful utility function that has various applications in programming. Let’s look at the some common uses of the max() function:
1. Finding the Maximum Value: The primary use of the max() function is to find the maximum value among a set of values. It can also determine the largest element in an array, the maximum score in a list of scores, or the highest price among a collection of prices.
Example:
int arr[] = {5, 2, 8, 1, 9};
int maxVal = max({arr[0], arr[1], arr[2], arr[3], arr[4]});
// maxVal will be 9
2. Comparison and Decision Making: The max() function can be used in conditional statements and decision-making processes. It allows you to compare values and make decisions based on the maximum value.
Example:
int score1 = 85;
int score2 = 90;
int passingScore = 75;
if (max(score1, score2) >= passingScore) {
cout << "At least one student passed the exam." << endl;
} else {
cout << "Both students failed the exam." << endl;
}
3. Sorting and Selection: The max() function can be used as a helper function in sorting & selection algorithms. It can be used to find the maximum element in a subrange of an array or to select the largest value among multiple options.
Example:
// Finding the second largest element in an array
int arr[] = {5, 2, 8, 1, 9};
int largest = max({arr[0], arr[1], arr[2], arr[3], arr[4]});
int secondLargest = max({arr[0], arr[1], arr[2], arr[3], arr[4], largest});
// secondLargest will be 8
4. Bounding and Clamping: The max() function can be used to enforce upper bounds or clamp values within a certain range. It ensures that a value does not exceed a specified maximum limit.
Example:
int value = 15;
int maxLimit = 10;
int boundedValue = max(value, maxLimit);
// boundedValue will be 15, as it is not clamped by the maxLimit
5. Customized Comparisons: The version of max() that accepts a comparison function allows you to define custom ordering criteria for determining the maximum value. This is useful when working with user-defined types or when you need to compare objects based on specific attributes.
Example:
struct Person {
string name;
int age;
};
bool compareByAge(const Person& p1, const Person& p2) {
return p1.age > p2.age;
}
Person p1 = {"Rahul", 25};
Person p2 = {"Dev", 30};
Person olderPerson = max(p1, p2, compareByAge);
// olderPerson will be p2 (Dev), as the comparison is based on age
Examples of C++ max() Function
Let's look at some more examples to understand the use of the C++ max() function in different situations.
Example 1: Finding the Maximum Value in an Array
#include <iostream>
#include <algorithm>
int main() {
int arr[] = {10, 5, 8, 20, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int maxVal = max({arr[0], arr[1], arr[2], arr[3], arr[4]});
cout << "The maximum value in the array is: " << maxVal << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
The maximum value in the array is: 20
In this example, we have an array `arr` of integers. We use the max() function with an initializer list to find the maximum value among the array's elements. The max() function compares all the elements and returns the largest value, which is 20 in this case.
Example 2: Finding the Maximum Value Using a Comparison Function
#include <iostream>
#include <algorithm>
struct Person {
string name;
int age;
};
bool compareByAge(const Person& p1, const Person& p2) {
return p1.age > p2.age;
}
int main() {
Person p1 = {"Rahul", 25};
Person p2 = {"Dev", 30};
Person p3 = {"Sanjana", 20};
Person oldestPerson = max({p1, p2, p3}, compareByAge);
cout << "The oldest person is: " << oldestPerson.name << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
The oldest person is: Dev
In this example, we have a user-defined type `Person` with a name & an age. We define a comparison function `compareByAge` that compares two `Person` objects based on their age. We use the max() function with an initializer list of `Person` objects & provide the `compareByAge` function as the comparison function. The max() function uses the custom comparison defined by `compareByAge` to determine the oldest person among `p1`, `p2`, & `p3`. In this case, "Dev" is the oldest person with an age of 30.
Example 3: Clamping a Value within a Range
#include <iostream>
#include <algorithm>
int main() {
int value = 15;
int minLimit = 0;
int maxLimit = 10;
int clampedValue = max(minLimit, min(value, maxLimit));
cout << "The clamped value is: " << clampedValue << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
The clamped value is: 10
In this example, we have a value of 15 that we want to clamp within the range [0, 10]. We use the max() function in combination with the min() function to achieve this. The min() function ensures that the value does not exceed the `maxLimit` of 10, & the max() function ensures that the value is not less than the `minLimit` of 0. As a result, the clamped value is 10.
Related Functions in C++
In addition to the max() function, C++ provides many other related functions that can be useful in different scenarios. Let's discuss a few of these related functions:
1. min() Function:
The min() function is the counterpart of the max() function. It returns the minimum value among a set of values. The min() function has the same variations as the max() function:
- `min(value1, value2)`: Returns the smaller value between `value1` & `value2`.
- `min(initializer_list<T> il)`: Returns the minimum value among the elements in the initializer list `il`.
- `min(value1, value2, comp)`: Returns the minimum value between `value1` & `value2` based on the custom comparison function `comp`.
Example:
int minVal = min(5, 10); // minVal will be 5
int minVal2 = min({5, 2, 8, 1, 9}); // minVal2 will be 1
2. minmax() Function:
The minmax() function returns a pair of values representing the minimum & maximum values among a set of values. It has the following variations:
- `minmax(value1, value2)`: Returns a pair containing the minimum & maximum values between `value1` & `value2`.
- `minmax(initializer_list<T> il)`: Returns a pair containing the minimum & maximum values among the elements in the initializer list `il`.
- `minmax(value1, value2, comp)`: Returns a pair containing the minimum & maximum values between `value1` & `value2` based on the custom comparison function `comp`.
Example:
#include <iostream>
#include <utility>
using namespace std;
pair<int, int> minmax(int a, int b) {
if (a < b) {
return make_pair(a, b);
} else {
return make_pair(b, a);
}
}
int main() {
auto result = minmax(5, 10);
cout << "Minimum value: " << result.first << endl;
cout << "Maximum value: " << result.second << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
Minimum value: 5
Maximum value: 10
3. clamp() Function (C++17): The clamp() function is used to constrain a value within a specified range. It takes a value, a lower bound, and an upper bound and returns the value clamped within the range. If the value is less than the lower bound, it returns the lower bound. If the value is greater than the upper bound, it returns the upper bound. Otherwise, it returns the original value.
Example:
#include <iostream>
#include <algorithm> // For std::clamp
using namespace std;
int main() {
int value = 15;
int minLimit = 0;
int maxLimit = 10;
int clampedValue = clamp(value, minLimit, maxLimit);
cout << "Clamped value: " << clampedValue << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output
Clamped value: 10
4. max_element() and min_element() Functions: The max_element() and min_element() functions find the maximum and minimum elements in a range specified by iterators. They return an iterator pointing to the maximum or minimum element in the range.
Example:
#include <iostream>
#include <algorithm> // For std::max_element and std::min_element
using namespace std;
int main() {
int arr[] = {5, 2, 8, 1, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int* maxPtr = max_element(arr, arr + size);
int* minPtr = min_element(arr, arr + size);
cout << "Maximum element: " << *maxPtr << endl;
cout << "Minimum element: " << *minPtr << endl;
return 0;
}

You can also try this code with Online C++ Compiler
Run Code
Output:
Maximum element: 9
Minimum element: 1
Frequently Asked Questions
Can the max() function be used with user-defined types?
Yes, the max() function can be used with user-defined types as long as the appropriate comparison operator (>) or a custom comparison function is defined for the type.
What happens if the initializer list passed to max() is empty?
If an empty initializer list is passed to the max() function, it will result in undefined behavior. It is important to ensure that the initializer list contains at least one element.
Can the max() function be used to find the maximum value in a vector or other containers?
Yes, the max() function can be used with vectors or other containers by passing the begin and end iterators of the container to the max_element() function, which returns an iterator to the maximum element.
Conclusion
In this article, we have discussed the C++ max() function in detail. We learned about its different versions, parameters, return values, and exceptions. We also understood how the max() function works internally and explained many different use cases and examples. Moreover, we also discussed related functions like min (), minmax (), clamp (), max_element (), and min_element (). The max() function is a valuable tool in C++ for finding the maximum value efficiently among a set of values.
You can also check out our other blogs on Code360.