The Preprocessor Directives

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

The Preprocessor Directives

• The preprocessor provides the several tools that are unavailable in the any other
high level languages.
• The programmer can use these tools to make his program easy to read ,easy to
modify , portable and more efficient.
• It is program the process the “source code” before it passes through the
compiler.
• It operates under the control of what is known as “preprocessor command line”
or “directives.
• Preprocessor are placed in the program before the main line.
• Before the source code passes through the compiler , it is examined by the
“preprocessor “ for any preprocessor directives
Types of Directives
• Macro Substitution
• File inclusion
• Compiler control.

• Macro Substitution :
• It is process where identifier in program is replaced by a predefine string .
• The preprocessor do this task with the help of “#define” statement .
Syntax :
#define identifier String
 If this statement is in the program in the begining then the preprocessor replace every occurrence of the
identifier in the source code by the string.
The definition is not terminated by the semicolon .
Different forms of macro.
1. Simple Marco 2 . Argumented 3. Nested Macro
Simple Marco
• Example
• #define COUNT 100
• #define FALSE 0
• #Define PI 3.14
• #Define CAPITAL “Delhi”
•  Note that we have written all the Macro identifier in Capital to identify as symbolic constant .
Example
#define M 5
total = m *Value
printf(“ M=%d”, M)
Will replace as
Total = 5*value
printf(“M=%d”, 5)
• A macro substitution can include more then a simple constant value.
• #Define AREA 5*12.46
• #Define SIZE sizeof(Int) *4
• #define TWO_PI 2*3.14
While working with expression . Care should be taken to prevent an unexpected order of evaluation.
example:
ratio = D/A where D and A are macro defined as follows
#define D 45-22
#define A 78+32
The result of the preprocessor will be:
ratio= 45-22/78+32 will evaluate the wrong data
So the correct macro definition will be as follows .
#define D (45-22)
#define A (78+32)
The result of the preprocessor will be:
ratio= (45-22)/(78+32) , will evaluate the right data.
• Following are few definition that might
be useful in buliding error free and more
readable programs. Example:
#define EQUALS == START
#define AND && ………
#define OR || ………
#define NOT_EQUAL != If(total EQUALS 240 AND average 60)
#define START main() { INCREMENT count;
#define END } ………
#define MOD % END
#define BLANK_LINE printf(“\n”);
#define INCREMENT ++
Macro with Argument
• The preprocessor permits us to define more complex and more useful form of replacement .
Example 1:
• #define CUBE(x) (x*x*x)
if the following statement appear in the program later Volume= CUBE(side)
Then the preprocessor would expand this statement as following
Volume= (side*side*side)
Example 2: consider the following statement
volume=CUBE(a+b)
It expand to:
Volume= (a+b * a+b * a+b)
It will produce the correct result.so the currect defination of the macro should be as following
#define CUBE(x) ((x) * (x) *(x)) will expand to
Volume= ((a+b )* (a+b) * (a+b))
• Some commonly used macro defination are
• #define MAX(a,b) (((a) >(b)) ? (a) : (b))
• #define MIN(a,b) ((a)<(b)) ? (a) : (b))
• Nesting of Macro
• We can use one macro in the definition of another macro. It is called nested of macro.
#define M 5
#define N M+1
#define SQURE(x) ((x)*(x))
#define CUBE(x) (SQURE(x) * (x))
#define SIXTH(x) (CUBE(x) * CUBE(x))
a=SIXTH(x);
The definition will expand to first to
(CUBE(x) * CUBE(x)) then expand to

((SQUARE(x)*(x)) * (SQUARE(x) *(x)))


Since SQUARE(x) is still a macro so it will further expanded to
((((x) *(x) * (x) ) * (((x)* (x) ) *(x))) which is finally evaluated to x
6
Conditional preprocessor directives
EXAMPLE PROGRAM FOR  “#IFDEF”, “#ELSE” AND “#ENDIF” IN C:

•“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause statements are
included in source file.
•Otherwise, “else” clause statements are included in source file for compilation and execution.
•#include <stdio.h>
•#define PI 3.14
• 
void main()
{
   #ifdef PI
   printf(“PI is defined. So, this line will be added in " \
          "this C file\n");
   #else
   printf(“PI is not defined\n");
   #endif
   }
Output:
PI is define . So , this line will be added in this c file
 EXAMPLE PROGRAM FOR ”#IFNDEF” AND “#ENDIF” IN C:
•#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not
defined, “If” clause statements are included in source file.
•Otherwise, else clause statements are included in source file for compilation and
execution.
#include <stdio.h>
#define PI 3.14
void main()
{
   #ifndef SQUARE(x)
   {
      printf(“SQUARE is not defined. So, now we are going to define here\n");
      #define SQUARE(x) (x*X*X)
   }
   #else
   printf(“SQUARE is already defined in the program”);
   #endif
Output:
SQUARE is not defined. So, now we are going to define here
 EXAMPLE PROGRAM FOR  “#IF”, “#ELSE” AND “#ENDIF” IN C:
•“If” clause statement is included in source file if given condition is true.
•Otherwise, else clause statement is included in source file for compilation and execution.

#include <stdio.h>
#define a 100
void main()
{
   #if (a==100)
  printf("This line will be added in this C file since a \= 100\n");
   #else
   printf("This line will be added in this C file since a is not equal to 100\n");
#endif
   }
• EXAMPLE PROGRAM FOR “UNDEF” IN C LANGUAGE:
• This directive undefines existing macro in the program. #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);
}
• Output:
 First defined value for height : 100
 value of height after undef & redefine : 600
• EXAMPLE PROGRAM FOR “PRAGMA” IN C LANGUAGE:
“Pragma” is used to call a function before and after main function in a C program.
#include <stdio.h>
void function1( );
void function2( );
 #pragma startup function1
#pragma exit function2
  void main( )
{ printf ( "\n Now we are in main function" ) ; }
void function1( ) {
   printf("\nFunction1 is called before main function call"); }
void function2( )
{ printf ( "\nFunction2 is called just before end of main function" ) ; }

• Function1 is called before main function call


• Now we are in main function
• Function2 is called just before end of main function
The scope , Visibility and lifetime of
variables
• Variables in C differ in behavior from those in most other language . For
example , in a BASIC program , a variable return its value throughout the
program .
• It all depends on the “Storage” class a variable may assume.
• All variables in C have a data type , they also have a storage class.
• The following variable storage are most relevant to functions.
• Automatic variables
• External variables
• Static Variables
• Register Variables
• The scope , Visibility and lifetime of variables
• The scope of a variable defined the sections of a program from where a variable
can be accessed. The scope of variable depends upon it's place of declaration.
• There are three places where a variable can be declared in a C program:

• Outside of all functions(including main). This type of variables are known as


“global” variables.

• inside a function or inside a block of code. This type of variables are known as
“local” variables.

• Declared as the formal parameter in a function definition. This is similar to a local


variable in scope of function's body.
“Local Variables (Automatic variable) in C”
Local variables in C are declared inside a function body or block of
code(inside {} braces).
• Local variables can only be accessed by other statements or expressions
in same scope.

• Local variables are not known outside of their function of declaration or


block of code.

• Local variables gets created every time control enters a function or a


block of code. When control returns from function or block of code, all
local variables defined within that scope gets destroyed.

• By default, local variables contains garbage values unless we initialize it.


• A variable declared inside a function without storage class specification is , by default
an automatic variable.
• For example , the storage class of the variable number in the example below is
automatic
• Mian()
{
Int number;
---------------;
---------; }
We may also use the keyword auto to declare automatic variables explicitly.
• Mian()
{
Auto Int number; }
 One important feature of automatic variable is that their value can not be changed even
accidently by what happen in some other function in the program
External variables
• Variables that are both alive and active throughout the entire program are known as “external”
variable.
• They are also known as global variable . Unlike local global variables can be accessed by any function
in the program .
• External variables are declared outside a function
• Int number;
• Float length =7.25
• Void main()
• {……
• …….}
• Function 1()
• {……}
• Function2()
• {……..}
The variable “length” and number are available for use in all the three function .
In case a local variable and a global variable have the same name then the local variable will have precedence over the global one the
function
• One other aspect of a global variable is that it is available only from the
point of declaration to the end of the program.
• Consider a program segment as shown below
• Main()
{
y=5;
……… }
Int y ; // global declaration
Function1()
{
y=y+1; }
We have a problem here . As far as main concerned , y is not defined so the complier will issue
an error message .
• So the above problem can be solved by declaring the variable with storage class “extern”
• Main()
{
extern int y; // external declaration
……… }

Function1()
{
extern int y; // external declaration
………..
}
Int y; // definition

Note: although the variable “y” has been define after both function , the external declaration of “Y” inside the
function inform the compiler that “y” is an integer type define somewhere else in the program
Static variables
• As the name suggests , the value of a static variable persist until the end of
the program
• A variable can be declared “static” using the keyword “static” as follow
static int x;
static float y;
A static variable may either an “internal” type or “external” type
depending on the place of declaration
Internal static variables are those which are declared inside a function .
The scope of internal static variable extend up to the function in which
they are declared .
Therefore , internal static variable are similar to “auto” variables, expect
that they remain in existence(alive) throughout the program.
• Example: Output :
void stat(void)
x:->1
x:->2
void main()
x:->3
{ int i;
for(i=1;i<=3;i++)
{
stat(); }
Void stat(void)
{ static int x=0;
x= x+1;
printf(“x:->%d\n”, x); }
Note :
A static variable is initialized only once during the compile time ,
when the program is complied . It is never declared again .
During the first call to “Stat()” , x is incremented by 1 Bcoz x is
static then on second call incremented by 1 again and the value
of become 2. on third call the value of x again incremented by 1
and become 3
If x was not declared as “Static” the out will be as following Output:->
x:->1
x:->1
x:->1
Register storage class Variables
• Registers are faster than memory to access, so the variables which are
most frequently used in a C program can be put in registers
using register keyword.
•  The keyword register hints to compiler that a given variable can be put
in a register. It’s compiler’s choice to put it in a register or not.
• Generally, compilers themselves do optimizations and put the variables
in register.
• There is no limit on number of register variables in a C program, but the
point is compiler may put some variables in register and some not.
register int i;
Scope rules
• Scope
• The region of a program in which a variable for use.
• Visibility
• The program’s ability to access from the memory.
• Lifetime
• The lifetime of a variable is the duration of time in which a variable exist in
the memory during execution.
• The scope of a “global” variable is the entire program file.

• The scope of a “local” variable begins at point of declaration and ends at


the end of block or function in which it is declared .

• The life of an “AUTO” variable declared in the main is the entire program
execution time , although its scope only the “main” function

• The life of an “AUTO” variable declared in a function ends when the


function.

You might also like