Errors / Mistakes / Misuse of C Preprocessor in C
1 . Macro expansion should be enclosed within parenthesis
#include<stdio.h> #include<conio.h> #define SQU(x) x*x void main() { int num ; clrscr(); num = SQU(2)/SQU(2); printf("Answer : %d",num); getch(); }
Output :
Answer : 4
How ? Answer should be 1 not 4 then how it happens ?
- SQU(x) / SQU(x) is expanded as [ x*x / x*x ] = [ x * x ]
- As the macro #define only substitutes the SQU(2) by just 2*2 not by 4 .
- So SQU(2)*SQU(2) = 2*2/2*2 = 4
How to avoid this problem ?
#define SQU(x)((x)*(x))
2 .Do not Leave blank between macro-template and its argument
#define SQU(x)((x)*(x))//Write like this
- Do not give space between SQU and (x) , as it becomes the part of macro expansion
- It results into Improper result OR Compile time Error
3 . Do not Give semicolon at the end of #define statement .
#define SQU(x)((x)*(x));//Do not give semicolon at the end
4 . Allot one line for each macro preprocessor
#include<stdio.h> #include<conio.h>// Write on separate line
Do not write like this
#include<stdio.h>#include<conio.h>
good work!! congratz!!