Search code examples
cc-preprocessorminimum

C Macro for minimum of two numbers


I want to make a simple macro with #define for returning the smaller of two numbers.

How can i do this in C ? Suggest some ideas, and see if you can make it more obfuscated too.


Solution

  • For slightly obfuscated, try this:

    #define MIN(a,b)  ((((a)-(b))&0x80000000) >> 31)? (a) : (b)
    

    Basically, it subtracts them, and looks at the sign-bit as a 1-or-0. If the subtraction results in a negative number, the first parameter is smaller.