#define sqr(a) a*a x = 100/sqr(5);
Answer: value of x will be 100
Surprised! Let us expand the macro in the statement and see how it happened.
x = 100 / 5 * 5; x = (100 / 5) * 5; /*Division has higher precedence*/ x = 20 * 5; x = 100;
The result will be as expected if while defining the macro, we enclose it in brackets like so
#define sqr(x) (a * a) Expanding the line x = 100 / (5 * 5);/*macro replacement*/ x = 100 / 25; x = 4;
This happens because the C preprocessor replaces macro calls with the macro value as it is, rather than treating it as a pointer to a memory location like in function calls. Please be careful while dealing with macros in the future.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Learn on Youtube