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:

  • x: the first number to compare. Allowed data types: any data type.
  • y: the second number to compare. Allowed data types: any data type.

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.

int a = 25;
int b = 14;

void setup() {
  Serial.begin(9600);

  int min = min(a, b);

  Serial.print("The smaller value is: ");
  Serial.println(min);
}

void loop() {
}

Another typical application could be to constrain a maximum value of a variable, as shown in the following example:

sensVal = min(sensVal, 100);  // assigns sensVal to the smaller of sensVal or 100
                              // 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 results

min(a++, 100);  // avoid this - yields incorrect results

min(a, 100);
a++;  // use this instead - keep other math outside the function

See also