Preprocessor Notes

PREPROCESSOR 

   The preprocessor makes programs easier to develop and modify. The preprocessor makes C code more portable between different machine architectures and customize the language.


   The C Preprocessor is not part of the compiler, but is a separate step in the compilation process.


  The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. All preprocessor lines begin with #.


 Preprocessing directives are lines in your program that start with ‘#’. Whitespace is allowed before and after the ‘#’. The ‘#’ is followed by an identifier, the directive name. It specifies the operation to perform.


 The ‘#’ which begins a directive cannot come from a macro expansion. Also, the directive name is not macro expanded. Thus, if foo is defined as a macro expanding to define, that does not make ‘#foo’ a valid pre-processing directive. A pre-processing directive cannot cover more than one line. The line may, however, be continued with backslash-newline.

C Pre-processor is just a text substitution tool on your source code in three ways: File inclusion, Macro substitution, and Conditional compilation.


FORMAT OF PREPROCESSOR DIRECTIVE


      In C we can use preprocessor directives anywhere in our program. But it is preferable to use them at the beginning of the program.


      Preprocessor directives are placed in the source program before calling the main() function. It begins with a # symbol. They are never terminated with a semicolon (;).

Before source code passes through the compiler, it is examined by the preprocessor for any preprocessor directive. If there is any, appropriate actions are taken and then source code is handed over to compiler.

MACRO SUBSTITUTION DIRECTIVE (#define)    


 Macro substitution has a name and replacement text, defined with #define directive. The preprocessor simply replaces the name of macro with replacement text from the place where the macro is defined in the source code.


    Macro is an abbreviation for sequence of instruction. When this abbreviation is encountered in a program then defined sequence of instructions are submitted over there. This process is called macro substitution.


      Syntax:    #define identifier replacement_text       

/* Program for simple macro */

#define A 15

void main()

{

int x;

x=A;

printf(“%d %d”,x,A);

}

Nested Macros


      In C programming one macro can be used in the definition of another macro.


      Macro name within another macro called nesting of macro. A macro body may also contain further macro definitions. However, these nested macro definitions aren't valid until the enclosing macro has been expanded! That means, the enclosing macro must have been called, before the nested macros can be called.


      The called macro is inner macro and the calling macro is outer macro.

/* Program to find the square and cube of any given number using macro directive */

# include<stdio.h>

# define sqr(x) (x * x)

# define cub(x) (sqr(x) * x)

int main()

{

int num;

clrscr();

printf(“Enter a number: ”);

scanf(“%d”, &num);

printf(“ \n Square of the number is %d”, sqr(num));

printf(“ \n Cube of the number is %d\n”, cub(num));

return 0;

}

OUTPUT:             Enter a number: 5

                                      Square of the number are 25

                              Cube of the number is 125



FILE INCLUSION DIRECTIVES (#include)

      The preprocessor directive #include is an instruction to read in the entire contents of another file at that point. This is generally used to read in header files for library functions. Header files contain details of functions and types used within the library.

       Header files serve two purposes.

  1. System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations
  2. Your own header files contain declarations for interfaces between the source files of your program.

MACRO VS FUNCTION 

Macro

Function

Macro is Preprocessed

Function is Compiled

No Type Checking is done in Macro

Type Checking is Done in Function

Using Macro increases the code length

Using Function keeps the code length unaffected

Speed of Execution using Macro is Faster

Speed of Execution using Function is Slower

Before Compilation, macro name is replaced by macro value

During function call, transfer of control takes place

Macros are useful when small code is repeated many times

Functions are useful when large code is to be written

Macro does not check any Compile-Time Errors

Function checks Compile-Time Errors

Macros do not check for compilation error which leads to unexpected output.

Function checks for compilation error and there is a less chance of unexpected output.



/* Program of Macro using function */

#include <stdio.h>

#define SQUARE(x)  x * x

int sqr(int x)

{

     return x*x;

}

main()

{

   printf("Use of sqr(). The value of sqr(3+2): %d\n", sqr(3+2));

   printf("Use of SQUARE(). The value of SQUARE (3+2): %d", SQUARE (3+2));

}

OUTPUT:           Use of sqr(). The value of sqr(3+2): 25

                             Use of SQUARE (). The value of SQUARE (3+2): 11




     File inclusion - inserts the contents of another file into your source file.


     Macro Substitution - replaces instances of one piece of text with another.


     The #include pre-processor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. Macro is defined by #define directive.


     Since macros are implemented as a textual substitution, by this the performance of program improves compared to functions.


Any computations that can be done on macros can also be done on functions. But there is a difference in implementations and in some cases, it will be appropriate to use macros than function and vice versa.

PRACTICE PRORGAM


Program 1: Write a Program in C to find the area of a rectangle

// Program to find the area of a rectangle

#include<stdio.h>

#define RECTANGLE(l,b) l*b

int main()

{

printf("Welcome to DataFlair tutorials!\n\n");

int length = 3, breadth = 4;

int area = RECTANGLE(length,breadth);

printf("The area is: %d\n", area);

return 0;

}

OUTPUT:      The area is: 12

 

Program 2: Write a Program in C for sum and product of two numbers using macros.

// Program for sum and product of two numbers using macros.

#include<stdio.h>
#define SUM(A, B) (A + B)
#define PROD(A, B) (A * B)

int main()
{
            int num1, num2, sum, product;
            printf("\nEnter the Two numbers\n");
            scanf("%d%d",&num1,&num2);
            sum=SUM(num1,num2);
            product=PROD(num1,num2);
            printf("\n\nSum of two numbers using Macros is:%d\n", sum);
            printf("\n\n\Product of two numbers using macros is:%d\n", product);
            return 0;
}

OUTPUT:      Enter the Two numbers

            4

            5

           Sum of two numbers using Macros is: 9

           Product of two numbers using macros is: 20

 

Program 3: Write a program in C to check maximum/minimum using macro

// Program to check maximum/minimum using macro

#include <stdio.h>

#define MAX(x, y) (x > y ? x : y)

#define MIN(x, y) (x < y ? x : y)

int main()

{

 int num1, num2;

 printf("Enter any two numbers to check max and min: ");

scanf("%d%d", &num1, &num2);

 printf("MAX(%d, %d) = %d\n", num1, num2, MAX(num1, num2));

 printf("MIN(%d, %d) = %d\n", num1, num2, MIN(num1, num2));

 return 0;

}

OUTPUT:      Enter any two numbers to check max and min: 10 20

            MAX(10, 20) = 20
                        MIN(10, 20) = 10

 

Program 4: Write a program in C to swap two numbers using macro

// Program to swap two numbers using macro

#include <stdio.h>

#define SWAP(x, y) (x ^= y ^= x ^= y)

main()

{

   int num1, num2;

   printf("Enter any two number to swap: ");

   scanf("%d%d", &num1, &num2);

   printf("Values before swapping\n");

   printf("num1 = %d, num2 = %d\n\n", num1, num2);

  SWAP(num1, num2);

  printf("Values after swapping\n");

  printf("num1 = %d, num2 = %d\n", num1, num2);

}

OUTPUT:      Enter any two number to swap: 10 20

                         Values before swapping

                        num1 = 10, num2 = 20

                       Values after swapping

                       num1 = 20, num2 = 10

Program 5: Write a program in C to check even or odd number using macro

//  Program to check even or odd number using macro

#include <stdio.h>

#define IS_ODD(x) (x & 1)

int main()

{

   int num;

   printf("Enter any number to check even or odd: ");

  scanf("%d", &num);

  if (IS_ODD(num))

             printf("%d is ODD\n", num);

  else

printf("%d is EVEN\n", num);

 return 0;

}

OUTPUT:                  Enter any number to check even or odd: 22

                        22 is EVEN


Comments