Trying to figure out something simple in a C macro, like this code for example:
#include
#define MACRO(b) printf(\"%d\\n\", b*b)
int main(
When you use the macro, the preprocessor replaces it and its arguments quite verbatim, so the macro expansion in your code will look like
printf("%d\n", 4+1*4.1);
That will not provide you with the result you want, and it is one of the reasons that function-like macros are looked down upon.
You need to use parentheses to make sure this problem doesn't occur:
#define MACRO(b) printf("%d\n", (b)*(b))
while will then result in the following expansion:
printf("%d\n", (4+1)*(4.1));
Whenever you have problems with something preprocessor related, there are options for just about all compilers to stop after the preprocessing stage, which allows you to look at the preprocessed source and which will help you with problems like this.
Also note that another possible problem here is if the expression you pass as argument to the macro is e.g. a function call with some side-effect that function will be called twice and the side-effect will be happen twice, even when using parentheses.
A simple example, using your macro:
int my_function(void)
{
printf("Foo\n");
return 1;
}
int main(void)
{
MACRO(my_function());
}
The above program will print "Foo\n"
twice. If MACRO
was a proper function the call to my_function
would only happen once and the printout from the function would only happen once.
Put parentheses around your macro to evaluate arguments in the correct order:
#include <stdio.h>
#define MACRO(b) printf("%d\n", (b)*(b))
int main()
{
MACRO(4+1);
}