Preprocessor in C

Preprocessor directives are actually the instructions to the compiler itself.

They are operated directly by the compiler.

 

The most common preprocessor directives are:

  • include directive
  • define directive

 

include directive:

The include directive is used to include files.

Example :

    #include <stdio.h>

Here, stdio.h is a header file and the preprocessor replace the above line with the contents of header file.

 

define directive :

It is used to assign names to different constants or statements which are to be used repeatedly in a program.

These defined values or statement can be used by main or in the user defined functions as well.

 

Preprocessing directive #define has two forms.

  • #define identifier token_string
  • Macros with argument

NOTE :

  • Preprocessor statements begin with a hash symbol(#).
  • Preprocessors are NOT terminated by a semicolon.

Define identifier token

token_string : is optional but, are used almost every time in program.

E.g.

#define x 2

Whenever x occurs, it is replaced by the token string 2.

 

Example :

    #include <stdio.h>
    #define PI 3.1415
    int main(){
	int radius;
	float area;

	printf("Enter the radius : ");
	scanf("%d",&radius);

	area=PI*radius*radius;
	printf("\nArea=%.2f",area);
	return 0;
    }

 

Output :

Enter the radius : 2
Area=12.57

 

Explanation :

The PI is a define directive and is replaced by its value in every occurrence.

 Macro with argument

#define can be used to write macro definitions with parameters.

Syntax :

#define identifier(identifier 1,.....identifier n) token_string

Token string: is optional but used in every case.

Example :

    #include <stdio.h>
    #define PI 3.1415
    #define area(r) (PI*(r)*(r))
    int main(){
         int radius;
         float area;
         printf("Enter the radius : ");
         scanf("%d",&radius);

         area=area(radius);
         printf("\nArea=%.2f",area);
         return 0;
    }

 

Output :

Enter the radius :
Area=12.57

 

Explanation :

Every time the program encounters area(radius), it will be replace by (3.1415*(r)*(r)).