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

后端 未结 4 517
故里飘歌
故里飘歌 2021-01-05 02:17
 #define max(a,b) \\
   ({ typeof (a) _a = (a); \\
       typeof (b) _b = (b); \\
     _a > _b ? _a : _b; })

Why not simply (a>b ? a :

4条回答
  •  既然无缘
    2021-01-05 03:14

    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 :-)

提交回复
热议问题