max()

Description

Calculates the maximum of two numbers.

Syntax

max(x, y)

Parameter Values

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

Return Values

  • The larger of the two parameter values.

Example Code

void setup() { Serial.begin(9600); int x = 2; int y = 3; int z = max(x, y); Serial.print("x = "); Serial.println(x); Serial.print("y = "); Serial.println(y); Serial.print("max = "); Serial.println(z); } void loop() {}

The result in Serial Monitor:

Newbiely | Arduino IDE 2.3.8
──
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
x = 2 y = 3 max = 3
Ln 11, Col 1
Arduino Uno on COM15
2

※ 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 results

max(a--, 0); // avoid this - yields incorrect results // use this instead: max(a, 0); a--; // keep other math outside the function

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables .

※ OUR MESSAGES