Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use the max() function in C++

Harsh Jain

The max() function in C++ accepts two values and returns the larger one. This function is available in <algorithm.h>. The max() function helps during coding contests when you want to find the maximum of two values in the logic. Instead of writing this logic explicitly, you can thus use this function as-is.


The max() function accepts the following parameters.

  • first_value: This is the first value that we want to compare.

  • second_value: This is the second value to compare with the first one.

    You need to pass two values of the same type.

  • comparator: This is an optional parameter that specifies the condition when the first value should come and when the second value should come. In other words, you can pass a function that returns a Boolean value that denotes which value to pick out of the two given values.


The max() function returns the maximum value from the two given values.


Let’s look at the code now.

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  int int_result = max(10, 20);
  cout << "Maximum is: " << int_result << endl;

  char char_result = max('a', 'b');
  cout << "Maximum is: " << char_result;
  return 0;
Use max() function in C++


  • In lines 1 and 2, we import the required header files.
  • In line 6, we call the max() function and pass two integer values.
  • In line 7, we print the maximum of the two integers.
  • In line 9, we again call the max() function, but here we pass two character values.
  • In line 10, we print the maximum of the two character values.



View all Courses

Keep Exploring