Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAX using typeof extension of gcc

Tags:

c

gcc

macros

I have been programming in C for quite a while now.So I decided to learn a bit of advanced C.I heard of gcc compiler extensions.Below I saw a code for the MAX() that I till now has implemented as follows

#define MAX(x,y) ((x) > (y)? (x): (y))

This is the new definition that I found.Unfortunately I can't even understand what the below code does? and why would I do it as below instead of as above?

#define MAX(a,b)                    \
    ({                              \
    typeof (a) _a = (a);            \
    typeof (b) _b = (b);            \
    _a > _b ? _a : _b; })
like image 768
liv2hak Avatar asked Dec 09 '22 15:12

liv2hak


1 Answers

The advantage is that it avoids evaluating the arguments as many times as the classic macro.

By introducing local variables (using typeof to "clone" the type of the arguments), the actual expressions are only evaluated once, the return value is then simply using the local variable rather than evaluating the input expression again, as the classic macro has to do.

Compare what happens if called like this:

int a = 0, b = 1;
const int c = MAX(++a, ++b);

In the first case, because the input expressions have side-effects, the result will be hard to predict. In the second case, the arguments are only evaluated once so everything behaves as if MAX() was a regular function.

Also, your first macro example is failing to enclose the arguments in parenthesis everywhere, which is dangerous.

like image 156
unwind Avatar answered Dec 11 '22 11:12

unwind