Common C Programming Mistakes : Preprocessor Errors



Errors Or [ Mistakes/Misuse] of C Preprocessor in C :

Preprocessor processes given source code before giving it to the compiler.Preprocessor must be used with care. Some of the Common mistakes while using preprocessor are as below -

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

Explanation of Program :

Above expression will be expanded as -

SQU(x) / SQU(x) = [ x*x / x*x]
                = [ x*x/x*x  ]
                = [   x*x    ]
                = [   x^2    ]

In the program the macro #define substitutes SQU(2) by just 2*2 not by 4. thus -

SQU(2) / SQU(2) = [ 2*2 / 2*2]
                = [ 2*2/2*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>