Please take a look at this small code snippet:
#include <stdio.h>
#define BAR
int main(int argc, char *argv[])
{
int foo = 1;
foo = BAR(1, 2, 3);
printf("%d\n", foo);
return 0;
}
Since BAR
is defined as an empty macro, I'd estimate the line foo = BAR(1, 2, 3);
to be evaluated as
foo = ;
and cause a syntax error. However, that doesn't happen. In fact, the code above compiles just fine and for some reason foo
will be set to 3
, i.e. the last parameter to the BAR
macro. I can't make any sense of this. Can somebody shed some light onto why it is behaving like this? Is this defined behaviour in the C language?
You've defined BAR
as a "plain" macro, not a function-like macro, so it doesn't match BAR(1, 2, 3)
, only BAR
, so it expands to foo = (1, 2, 3)
.
To get what you expected, change the definition to a function-like macro:
#define BAR(...)