11 ms·
Can someone explain what the purpose of the safe min macro is? What is the advantage of this: #define min(a, b) ({ \ __typeof__ (a) _a = (a); \
by randlet 12y ago
Can someone explain what the purpose of the safe min macro is?
What is the advantage of this:
#define min(a, b) ({ \
__typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; \
})
over the naive
#define min(a, b) (((a) < (b)) ? (a) : (b))
?
- BudVVeezer 12y agoOne of the two values (a or b) gets evaluated twice. Eg) min(a++, b++); a or b would really be incremented twice.
- randlet 12y agoNice thanks. Makes perfect sense and I can see that making for a hair pulling debug session if you weren't aware of it.
- AceJohnny2 12y agoIt's the kind of thing that's made me very familiar with the -E option for GCC, which makes it spit out the preprocessed code...
- ctz 12y agoIt evaluates its arguments once. That means min(expensive_calculation(x), expensive_calculation(y)) works how it reads. A compiler might be able to avoid this if it can prove expensive_calcluation is pure, but this is usually not done unless WPO is in play.
- rmfr 12y agoThe purpose is to evaluate `a` and `b` only once; consider `min(i++, j)`.
- jws 12y agoThe linux kernel goes one step further and includes… (void) (&_a == &_b); \ … which makes sure that the types are actually compatible, and not just having one converted to the other.