This is a very simplified version of some code I just ran into at work:
#include <stdio.h>
#define F(G) G(1)
#define G(x) x+1
int main() {
printf("%d\n", F(G));
}
prints 2.
Now, I can see that F(G) expands to G(1) and then G(1) expands to 2, but its not clear to me why. I would have expected to get an error that G is not a function from the printf line.
How does the pre-processor parse code like this?
A function-like macro is only invoked if its name is followed by a
(.In
F(G),Gis not followed by a(, so theGthere is not a macro invocation.In
F(G) G(1),Gis a macro parameter and thus is not macro-replaced directly (this is a very confusing macro you’ve got :-O). InG(1),Gis replaced by the argument corresponding to the parameterG, which also happens to beG. That replacement is then rescanned andG(1)is evaluated to1 + 1.If we rewrite your macros so that you aren’t using
Gin multiple different ways, it’s far easier to understand:Here,
F(G)is replaced byG(1). This is then rescanned, and the invocation ofGis evaluated, yielding1 + 1.