max()
Description
Find the larger of two numbers using the
max()
function.Syntax
Use the following function to compare two numbers and find the larger:
max(x, y)
Parameters
The function admits the following parameters:
: the first number to compare. Allowed data types: any data type.x
: the second number to compare. Allowed data types: any data type.y
Returns
This function returns the larger of the two parameter values compared.
Example Code
Compares
a
and b
and print the larger variable in the Serial Monitor.1int a = 25;2int b = 14;3
4void setup() {5 Serial.begin(9600);6
7 int max = max(a, b);8
9 Serial.print("The larger value is: ");10 Serial.println(max);11}12
13void loop() {14}
Another typical application could be to constrain a minimum value of a variable, as shown in the following example:
1sensVal = max(sensVal, 20); // assigns sensVal to the larger of sensVal or 202 // (effectively ensuring that it is at least 20)
Notes and Warnings
Perhaps counter-intuitively,
max()
is often used to constrain the lower end of a variable’s range, while min()
is used to constrain the upper end of the range.Because of the way the
max()
function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results1max(a--, 0); // avoid this - yields incorrect results2
3// use this instead:4max(a, 0);5a--; // keep other math outside the function
See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.