Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

macros

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

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

like image 275
compiler Avatar asked Mar 16 '11 10:03

compiler


People also ask

Why do we use #define MAX in C?

In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables.

How are macros defined in C?

The macro in C language is known as the piece of code which can be replaced by the macro value. The macro is defined with the help of #define preprocessor directive and the macro doesn't end with a semicolon(;).

Is Max defined in C?

max is an inline function (implemented using GNU C smart macros) which returns the greater of a and b. They may be any numeric values, either integer or floating point numbers, and they also may be pointers to the same base type.

What does Max () do in C?

Description: The max() function returns the greater of two values. The max() function is for C programs only. For C++ programs, use the __max() macro.


1 Answers

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

like image 54
xanatos Avatar answered Sep 18 '22 13:09

xanatos