Have you seen MIN and MAX macro in Objective-C

How will you write a MIN(a, b) or MAX(a, b) macro?

In the real world, it is easy to tell which is the minimum and which is the maximum of 2 numbers. But to write a correct function in computer, it’s not an easy job as we can see.

Usually, MIN and MAX functions are written in macro, so how will you write it?

#define MYMIN1(a, b) {a < b ? a : b;}

This is definitely wrong, at least you need to add the parenthesis to the parameters. OK, it’s easy, let’s add this:

#define MYMIN2(a, b) ({(a) < (b) ? (a) : (b);})

But, this is still wrong. Let’s take a look at what Objective-C and other languages defines these 2 macros.

How does Objective-C define MIN and MAX?

Because there is no MIN or MAX defined by C standard library, Objective-C defined this in NSObjCRuntime.h

Let’s see the code:

#if !defined(MIN)
#define MIN(A,B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __a : __b; })
#endif

#if !defined(MAX)
#define MAX(A,B)    ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a < __b ? __b : __a; })
#endif

Wow! that’s extremely long. Let’s see why it is necessary. Say your user write a piece of code like this:

int i=1, j=2;
int r = MIN(i++, j++);

What’s the supposed result of r? Obviously, it should be 2, but if you use MYMIN2, you got 3.

That’s why MIN and MAX are defined so complicated in Objective-C and other languages.

Make sure MIN/MAX does not change the value passed in

That’s the key point of write MIN and MAX in macro.

__typeof__(A) __a = (A);

is the key point to the correct result.


Don’t forget to follow me @TonnyXu

Be Sociable, Share!