Search code examples
cmacros

Why is the 'max' macro defined like this in C?


 #define max(a,b) \
   ({ typeof (a) _a = (a); \
       typeof (b) _b = (b); \
     _a > _b ? _a : _b; })

Why not simply (a>b ? a : b)?


Solution

  • because otherwhise max(f(1), f(2)) would call one of the two functions twice:

    f(1) > f(2) ? f(1) : f(2)
    

    instead by "caching" the two values in _a and _b you have

    ({
        sometype _a = (a);
        sometype _b = (b);
    
        _a > _b ? _a : _b;
    })
    

    (and clearly as other have pointed out, there is the same problem with autoincrement/autodecrement)

    I don't think this is supported by Visual Studio in this way. This is a compound statement. Read here does msvc have analog of gcc's ({ })

    I'll add that the definition of compound statement in the gcc manual given here http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC62 shows a code VERY similar to the one of the question for max :-)