Taking advantage of short-circuiting in boolean expressions:
int max(int a, int b, int c)
{
int m = a;
(m < b) && (m = b); //these are not conditional statements.
(m < c) && (m = c); //these are just boolean expressions.
return m;
}
Explanation:
In boolean AND
operation such as x && y
, y is evaluated if and only if x
is true. If x
is false, then y
is not evaluated, because the whole expression would be false which can be deduced without even evaluating y
. This is called short-circuiting when the value of a boolean expression can be deduced without evaluating all operands in it.
Apply this principle to the above code. Initially m
is a
. Now if (m < b)
is true, then that means, b
is greater than m
(which is actually a
), so the second subexpression (m = b)
is evaluated and m
is set to b
. If however (m < b)
is false, then second subexpression will not be evaluated and m
will remain a
(which is greater than b
). In a similar way, second expression is evaluated (on the next line).
In short, you can read the expression (m < x) && (m = x)
as follows : set m
to x
if and only if m
is less than x
i.e (m < x)
is true. Hope this helps you understanding the code.
Test code:
int main() {
printf("%d
", max(1,2,3));
printf("%d
", max(2,3,1));
printf("%d
", max(3,1,2));
return 0;
}
Output:
3
3
3
Note the implementation of max
gives warnings because evaluated expressions are not used:
prog.c:6: warning: value computed is not used
prog.c:7: warning: value computed is not used
To avoid these (harmless) warnings, you can implement max
as:
int max(int a, int b, int c)
{
int m = a;
(void)((m < b) && (m = b)); //these are not conditional statements.
(void)((m < c) && (m = c)); //these are just boolean expressions.
return m;
}
The trick is that now we're casting the boolean expressions to void
, which causes suppression of the warnings: