I see two possible implementations for a MAX macro in C. Which of these would be best?
define MAX(X,Y) ((X) < (Y) ? : (Y) : (X))
define MAX(X,Y) 0.5*(X+Y+ABS(X-Y))
I see two possible implementations for a MAX macro in C. Which of these would be best?
define MAX(X,Y) ((X) < (Y) ? : (Y) : (X))
define MAX(X,Y) 0.5*(X+Y+ABS(X-Y))
Second one is hard to read, and actually broken. Really bad idea.
I also recommend functions, and not macros so the arguments don't get evaluated twice.
There are occasionally situations where such tricky versions are appropriate. For example calculating the maximum of two integers in constant time. But they're rare, and certainly should not be used as the default implementation for MAX
.
The first version is more general, efficient and easier to understand.
The second version uses a floating-point constant, which makes it specific to doubles. It may potentially return the wrong answer since floating-point calculations may be rounded off. (due to the inability of a binary value to represent exactly every possible decimal value, 0.1 for example) There are also more calculations involved. The multiplication with 0.5 is not enclosed in parenthesis which may lead to unexpected results.
There's also the matter of compiler optimizations but I'm not going into that.