importance of enclosing macro expansion wihtin parentheses
/* Program to illustrate the importance of enclosing macro expansion wihtin parentheses */
If we fail to enclose the entire macro expansion in the parentheses then we may get some unexpected results.
Consider the following program:
#include<stdio.h>
#define SQUARE(x) x*x //Macro definition without parentheses
int main()
{
int i;
i=27/SQUARE(3);
printf("%d",i);
return 0;
}
Here we expected that the output would be 3.
Lets see the actual output:
Shocked, the reason is that the above macro is expanded as:
i=27/3*3;
Following the associativity rule (left to right) first 27/3 is solved which gives 9.
i.e. i=9*3;
So we get the out put as 27 not 3.
So how to write the macro for getting the correct out put.
Following program will illustrate you this thing.
#include<stdio.h>
#define SQUARE(x) (x*x) //Macro definition with parentheses
int main()
{
int i;
i=27/SQUARE(3);
printf("%d",i);
return 0;
}
0 comments: