Pre Processor Directives

The preprocessor is the first stage of compilation and the commands which are used at this stage of compilation are referred to as pre-processor directives.

It processes included files, conditional compilation, and macros. It converts high-level language into pure high-level language.

Common pre processor directives are:

# include:

This tells the preprocessor to include the content of the files to the current files. They include user-defined or system-defined header files which contain variables, function declarations, and macros.

Example:

#include <stdio.h> // including stdio.h header for printf() function
int main()
{
 printf ("\n Including header file stdio.h"\n);
 return 0;
}

Conditional compilation:

It is used for selectively compiling certain portions of source code depending upon certain conditions. One of the key advantages of having these directives is the portability of source code.

Example:

#include <stdio.h>
#define max 10
int main()
{
   #ifdef max
      printf("\n Max is defined\n");
   #else
      printf("\n Max is not defined\n");
   #endif
   
   #ifndef min
      printf("\n Min is not defined\n");
   #else
      printf("\n Min is defined\n");
   #endif
   return 0;
 }  

Output:

Max is defined
Min is not defined

Macros:

It is a block of code with a name, and if the name is found in the program, the complete piece of code is substituted at the place of a name. This is a text substitution that results in the expansion of the code.

#include <stdio.h>

#define square(x) (x * x)
int main()
{
  int x = 5;
  printf("\n The square of the number is: %d\n",square(x));
  return 0;
}

Output:

The square of the number is: 25

#pragma:

It is used to pass various instructions for compilation.

Some of the common directives are:

  • #pragma once : makes sure that any file is included just once
  • #pragma startup :# function gets executed even before main() (Syntax: #pragma startup fun)
  • #pragma exit : function gets executed before the program terminates (Syntax: #pragma exit fun)
  • #pragma pack(1) : This is used to avoid structure padding

Generic Syntax :

#pragma pack(n)

where n is alignment in bytes, valid values are 1, 2, 4 and 8 and by default is 8



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: