#define preprocessor directive



In this tutorial we will be learn how to use #define preprocessor directive in C programming.In C Programming, we can define constants using the #define preprocessor directive.

#define preprocessor directive

It is also called as simple substitution macro as it simply removes the occurrences of the constant and replace them using the expression

Syntax

#define macro_identifier value

where –

Syntax partExplanation
#defineIt is preprocessor directive used to define constant
macro_identifierIt is constant used in the program which we wish to declare using #define
valueIt is value of the constant

Important Note

  1. #define Preprocessor defines a constant/identifier and a value that is substituted for identifier/constant each time it is encountered in the source file
  2. Generally macro-identifiers/constant defined using #define directive are written in the capital case to distinguish it from other variables.
  3. constants defined using #define directive are like a name-value pair.

Examples

#define PI 3.142
#define TRUE 1
#define AND &&
#define LESSTHAN <
#define MESSAGE "welcome to C"

In this case –

ConstantValue of constantExpression
PI3.142Each occurrence of PI will be replaced by 3.142
TRUE1Each occurrence of TRUE will be replaced by 1
LESSTHAN<Each occurrence of LESSTHAN will be replaced by >
MESSAGEwelcome to CEach occurrence of TRUE will be replaced by 1

Live Example :

Step 1 : program.c [Program written by Programmer]

#include<stdio.h>
#define LESSTHAN <

int main()
{
int a = 30;
if(a LESSTHAN 40)
        printf("a is Smaller");

return(0);
}

Step 2 : Program is processed by Pre-processor

int main()
{
int a = 30;
if(a < 40)
        printf("a is Smaller");
return(0);
}

Step 3 : Program is processed by Compiler

a is Smaller

Precautions to be Taken while Writing Simple Preprocessor

  • Do not Write Semicolon After #define Statement.
#define MAX 20;