Macros in C

Macros in C


What is Macro ?

Macro is a segment of code that is given a name; which is replaced by statement or value of that macro. Macro is defined by #define preprocessor. 

In this tutorial you will learn :


Why do we need Macros ?

1. Macros make programs more readable.
2. Macros increase efficiency of programs and make it faster.

Types of Macro :

1. Object-like Macro :
This type of macro used for defining a constant value.
Syntax :
#define macro_name macro_value
Example :
#define PI 3.14
Program :
//Write a C program to check area of circle using #define preprocessor.
//or, Write a C program to check area of circle using Macro.

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


2. Function-like Macro :
This type of macro used for defining a argument.
Syntax :
#define macro_name argument
Example :
#define CIRCLE_AREA(r) (PI*r*r)
Program :
//Write a C program to check area of circle using #define preprocessor.
//or, Write a C program to check area of circle using Macro.

  #include<stdio.h>
  #define PI 3.14
  #define CIRCLE_AREA(r) (PI*r*r)
  int main()
  {
	float radius,area;
	printf("Enter the Radius: \n");
	scanf("%f",&radius);
	area=CIRCLE_AREA(radius);
	printf("Area is: %f",area);
	return 0;
  }  
Output :


Some predefined Macros :


1. __DATE__

Working Principle :
It shows current date as character literal in “MMM-DD-YYYY” format.
Program : 
//Write a C program to print current date using predefine Macro.
  
#include<stdio.h>
int main()
{
	printf("Current date is :%s\n",__DATE__);
	return 0;
}
Output :

2. __TIME__


Working Principle :
It shows current time as character literal in “HH:MM:SS” format.

Program : 
//Write a C program to print current time using predefine Macro.

#include<stdio.h>
int main()
{
printf("Present time is :%s\n",__TIME__);
return 0;
}
Output :
Present time is: 11:17:30

3. __FILE__


Working Principle :
It shows current file name as string literal .
Program :
//Write a C program to print file name using predefine Macro.

#include<stdio.h>
int main()
{
    printf("File name is :%s\n",__FILE__);
return 0;
}
Output :
File name is :Eruditors.c

4. __LINE__


Working Principle :
It shows current line number as decimal constant .

Program : 
//Write a C program to print line number using predefine Macro.

#include<stdio.h>
int main()
{
    printf("Line number is :%d\n",__LINE__);
    return 0;
}
Output :
Line number is:4

5. __STDC__


Working Principle :
It is defined as 1 when compiler complies with ANSI standard.
Program : 
//Write a C program to check program is ANSI standard or not using predefine Macro.

#include<stdio.h>
int main()
{
	printf("ANSI standard or not:%d\n",__STDC__);
    return 0;
}
Output :
ANSI standard or not:1