Comparing several values.
Never thought I'd be asking a "homework question", but this qualifies as one, since it is from the chapter review section of the book I'm reading (C Plus Primer, 5th ed., for the curious).
"Write a function that returns the largest of three integer arguments."
For two values it'd be an easy return a > b ? a : b;
For three (or more, I suppose), I came up with this. Could someone tell me if I'm over-engineering or give me a pointer to a better solution? I know that I sometimes tend to miss the obvious one.
Code:
int compare(int a, int b, int c) {
int max = 0;
int tmp[3] = {a, b, c};
for (int i = 0; i < 3; i++) {
if (tmp[i] > max) {
max = tmp[i];
}
}
return max;
}
Thanks for you time!