Common C Programming Mistakes : Preprocessor Errors



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 –

Mistakes while writing C Preprocessor directives :

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     ]

In order to avoid the above problem we can write like –

#define SQU(x)((x)*(x))

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

Do not Give semicolon at the end of #define statement .

#define SQU(x)((x)*(x));//Do not give semicolon at the end

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>