performance - Which of these C "MAX" macros would be best? -
I see two possible implementations for the maximum macro in C. Which of these would be best?
-
define MAX (X, Y) ((x) & lt; (y) ?: (y): (x)) < Li>
Define MAX (X, Y) 0.5 * (X + Y + ABS (XY))
The second is hard to read, and really broken is actually a bad idea.
- Second, always uses doubles. You will get round errors, I definitely do not expect to get a result which is not equal to either side.
- When applied to the whole, Floats is also promoted as double.
- If you "correct" it instead of "0.5" / 2, then those other types would "work", but you get an unexpected overflow on a large integer
I also recommend works, not macros, so the argument is not evaluated twice.
Sometimes there are situations where such difficult versions are suitable, for example, the calculation of the maximum two integers in constant time but they are rare, and of course < Code> MAX should not be used as a default implementation.
Comments
Post a Comment