3 ms·
Can someone explain this code please: #define min(x, y) ({ \ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ (void) (&_min1 == &_min2); \
by cabalamat 18y ago
Can someone explain this code please:
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
What does the 4th line do?
- blasdel 18y agoThis version omits it: http://en.wikipedia.org/wiki/C_preprocessor#Multiple_evaluation_of_side_effects http://en.wikipedia.org/wiki/C_preprocessor#Multiple_evaluat... It's pretty baffling, what's the point of checking the addresses-of for equality, and then casting it to void without assignment? It's not like it could throw an exception or anything :) The compiler would just optimize it out, so it must be there solely to cause compiler warnings, but I can't figure out any cases that it covers and the final statement does not.
- deleted 18y ago[deleted]
- yan 18y agoI believe it is to make sure that x and y are of comparable types. Comparing pointers of different types generates a warning with GCC. I can be wrong though..
- babo 18y agoYou are right, it's a compile time argument checking for type equality.
- deleted 18y ago[deleted]
- blasdel 18y agoThe real oddity of this macro is the parentheses around the block, which cause it to behave much like an inline function (but without having to wrestle the type system).
- deleted 18y ago[deleted]
- deleted 18y ago[deleted]
- yan 18y agoIt's also cleaner than the do { ... } while(0) business, imho.
- tspiteri 18y agodo { ... } while(0) is Ansi C and has type void. ({ ... }) is a GCC extension and its value is the value of the last expression inside the block. So they have different uses.
- davidw 18y agoWith and without it, trying to compile this: long a = 10; int b = 20; printf("min is %ld\n", min(a, b)); With, it generates a warning: davidw@fortrock:/tmp$ gcc -o min min.c min.c: In function ‘main’: min.c:13: warning: comparison of distinct pointer types lacks a cast Without, there is no warning.