Reputation: 2913
The file windef.h
defines the min/max functions using macros as follows:
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
It has been noted, however, that such a definition:
What I do not understand is:
__typeof__ (a) _a = (a); __typeof__ (b) _b = (b);
helps with type safety and why is it not double evaluation in this case?Upvotes: 2
Views: 363
Reputation: 213990
Why/where is there double evaluation?
The easiest way to understand this is to run this code:
#include <stdio.h>
#define max(a,b) ((a)>(b)?(a):(b))
int f1 (void)
{
printf("%s executed.\n", __func__);
return 1;
}
int f2 (void)
{
printf("%s executed.\n", __func__);
return 2;
}
int main (void)
{
printf("Max: %d", max(f1(), f2()) );
}
Output:
f1 executed.
f2 executed.
f2 executed.
Max: 2
The function f2() is called twice, because the macro parameter b
is evaluated twice.
How does the trivial redefinition
__typeof__ (a) _a = (a); __typeof__ (b) _b = (b);
helps with type safety and why is it not double evaluation in this case?
Because that code creates two temporary variables and stores the result of the evaluation there, once per variable.
Please note that __typeof__
as well as the ({ ... })
syntax are not standard C and should be avoided. The macro from the linked accepted answer is quite ugly and not something I would recommend.
The sane solution is to not use a macro but a function:
static inline int max (int a, int b)
{
return a > b ? a : b;
}
Notice how readable the code turns out, compared to the macro mess.
If you for some reason unknown must use macros, stick to standard C as shown here: https://stackoverflow.com/a/30918240/584518
Upvotes: 8