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; })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With