Friday, February 10, 2012

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; }) 

No comments:

Post a Comment