Find the largest of four integers using simple comparisons.
#include <stdio.h>
int max4(int a, int b, int c, int d) {
int m = a; /* the best so far */
if (b > m) m = b;
if (c > m) m = c;
if (d > m) m = d;
return m;
}
int main(void) {
printf("%d %d\n", max4(12, 45, 7, 45), max4(-3, -8, -1, -6));
return 0;
}
45 -1
Keeping a running maximum needs exactly three comparisons for four values and scales to any number of values, unlike nested if-else trees. Starting from a (not 0) handles negative numbers.