Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26655

Which of these C "MAX" macros would be best?

I see two possible implementations for a MAX macro in C. Which of these would be best?

  1. define MAX(X,Y) ((X) < (Y) ? : (Y) : (X))
  2. define MAX(X,Y) 0.5*(X+Y+ABS(X-Y))

Upvotes: 0

Views: 201

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108810

Second one is hard to read, and actually broken. Really bad idea.

  1. Second one always uses doubles. You will get rounding errors. I certainly wouldn't expect getting a result that's not equal to either side.
  2. When applied to integers it returns a double, quite surprising. Floats get promoted to double as well.
  3. If you "fix" it by replacing *0.5 with /2 it'd "work" on those other types, but you'd get unexpected overflows on large integers.

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.

Upvotes: 4

David
David

Reputation: 953

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.

Upvotes: 2

Related Questions