String
Structure

Preprocessor

Pre-processor

Preprocessor is a program that process our code before it passes through the compiler.It operates under the control of preprocessor command lines and directives.

The C preprocessor is a macroprocessor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to definemacros, which are brief abbreviations for longer constructs.

Declaration method

The most common preprocessor directive is

#include

Here, #include is a preprocessor directive and it makes header file like stdio.havailable for us.

Let’s take another example of a pre-processor directive.

#define PI 3.14

Here, #define is a pre-processor directive. It is used to define something, like here we have defined that PI is 3.14. So, before going to the compiler, if PI comes anywhere in the program, it will be replaced by 3.14.

Lets try an example for finding the area of circle.

#include<stdio.h>
#define PI 3.14
int main() 
{
  int radius; 
  float area; 
  printf("Enter radius of circle\n");
  scanf("%d", &radius);
  area = PI*radius*radius;
  printf("Area of circle is %.2f\n", area);
  return 0;
}

Enter radius of circle 

Area of circle is 50.24

PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:


#include<stdio.h>
 
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
 
void main()
{
   printf("value of height    : %d \n", height );
   printf("value of number : %f \n", number );
   printf("value of letter : %c \n", letter );
   printf("value of letter_sequence : %s \n", letter_sequence);
   printf("value of backslash_char  : %c \n", backslash_char);
 
}

value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

PROGRAM FOR UNDEF IN C LANGUAGE:

#include<stdio.h>
 
#define height 100
void main()
{
   printf("First defined value for height    : %d\n",height);
   #undef height          // undefining variable
   #define height 600     // redefining the same for new value
   printf("value of height after undef \& redefine:%d",height);
}
First defined value for height : 100
value of height after undef & redefine : 600

Macros with Arguments

Let’s see an example to print area of a circle using macros.

#include<stdio.h>
#define area(r) (3.14*r*r)
int main() 
{
  int radius; 
  float area; 
  printf("Enter radius of circle\n");
  scanf("%d", &radius);
  area = area(radius);
  printf("Area of circle is %.2f\n", area);
  return 0;
}
 

Enter radius of circle 

Area of circle is 50.24

Comments are closed.