I recently found this GCC macro:
#define max(a,b) \
({ typeof (a) _a = (a); \
typeof (b) _b = (b); \
_a > _b ? _a : _b; })
I didn’t realize before I saw this code, that a block of code {...} can somehow return value in C.
1) Could you give me a hint how this works?
Though, I usually was able to achieve the same result by abusing the comma operator:
#define max(a,b) \
(typeof (a) _a = (a), \
typeof (b) _b = (b), \
(_a > _b ? _a : _b))
or if it was only for side-effect I would use do { ... } while(0)
2) What is the preferred way of doing this?
The
({ ... })construct is a gcc extension.So is the
typeofoperator.A
MAXmacro (note the conventional use of all-caps) is easy enough to write:It does evaluate one of its arguments more than once, so you shouldn’t invoke it as, for example,
MAX(x++, y--). The use of all-caps serves to remind the user that it’s a macro, not a function, and to be careful about arguments with side effects.Or you can write a function (perhaps an inline one) for each type.