min()
Description
Find the smaller of two numbers using the
min()
function.Syntax
Use the following function to compare two numbers and find the smaller:
min(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 smaller of the two parameter values compared.
Example Code
Compares
a
and b
and print the smaller variable in the Serial Monitor.1int a = 25;2int b = 14;3
4void setup() {5 Serial.begin(9600);6
7 int min = min(a, b);8
9 Serial.print("The smaller value is: ");10 Serial.println(min);11}12
13void loop() {14}
Another typical application could be to constrain a maximum value of a variable, as shown in the following example:
1sensVal = min(sensVal, 100); // assigns sensVal to the smaller of sensVal or 1002 // ensuring that it never gets above 100.
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
min()
function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results1min(a++, 100); // avoid this - yields incorrect results2
3min(a, 100);4a++; // use this instead - 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.