B
bradeck
A question recently came up of late in some interviewing techniques
discussions and I vaguely remember this being an ANSI C++ related issue
but cannot remember the specifics. Basically if you have the following:
#define foo(x) x*x
..
..
..
foo(3+2);
Beside the obvious feau paux of not wrapping the macro parameter in
parens, the common misconception is the actual macro side affect - i.e.
the addition will take place before the substitution:
i.e. foo(3+2) = foo(5) = 5*5 = 25
Deeper insight believes that the substitution will take place first:
i.e. foo(3+2) = 3+2*3+2 = 3+(2*3)+2 = 11
However, it is my understanding the preprocessors can actually combine
literals (it's left to the implementation) giving a result of the
original first inclination:
i.e. foo(3+2) = foo(5) = 5*5 = 25
Now, in this case the point would be moot (and thuis the side affect
generated) if these were variables and not interger literals:
i.e.
int y= 3;
int z = 2;
foo(y+z) = y+z*y+z = y+(z*y)+z = (at run time) 3+(2*3)+2 = 11
Anyway, the question comes down to whether or not the preprocessor is
allowed to do mathematical calculations on integer literals. Anybody
know?
discussions and I vaguely remember this being an ANSI C++ related issue
but cannot remember the specifics. Basically if you have the following:
#define foo(x) x*x
..
..
..
foo(3+2);
Beside the obvious feau paux of not wrapping the macro parameter in
parens, the common misconception is the actual macro side affect - i.e.
the addition will take place before the substitution:
i.e. foo(3+2) = foo(5) = 5*5 = 25
Deeper insight believes that the substitution will take place first:
i.e. foo(3+2) = 3+2*3+2 = 3+(2*3)+2 = 11
However, it is my understanding the preprocessors can actually combine
literals (it's left to the implementation) giving a result of the
original first inclination:
i.e. foo(3+2) = foo(5) = 5*5 = 25
Now, in this case the point would be moot (and thuis the side affect
generated) if these were variables and not interger literals:
i.e.
int y= 3;
int z = 2;
foo(y+z) = y+z*y+z = y+(z*y)+z = (at run time) 3+(2*3)+2 = 11
Anyway, the question comes down to whether or not the preprocessor is
allowed to do mathematical calculations on integer literals. Anybody
know?