In c language, Macros are used repeatedly whenever we want to use a piece of code or a single value in a program. once macros are defined in a program, they can be used frequently throughout the program. in this article, we will learn what macros are in c language.
What is Macro?
A macro is a piece of code that has been given a name. whenever the name is used, it is replaced by the macro value. The macro is defined by the #define preprocessor directive and Marco doesn't end with a semicolon(;).
syntax
#define name value
example:
#define PI 324567
In this example above whenever we use PI in our program it will be replaced with 324567.
Program:
#include <stdio.h>
//PI is the macro name and 324567 the value
#define PI 324567
int main()
{
printf("value of PI is: %d", PI);
return (0);
}
Output:
value of PI is: 324567
Types of macros
- Object-like macros: In Object-like Macros, a macro is replaced by a code fragment.
let's look at an example using Object-like macros.
Program:
#include <stdio.h>
//Object-like macros definition
#define Date 25
int main()
{
printf("The Date for thanksgiving is %d March 2023", Date);
return (0);
}
Output:
The Date for thanksgiving is 25 March 2023
- Function-like Macros: In Function-like Macros, macros are the same as a function call. it replaces the entire code instead of a function name.
let's look at an example using Function-like Macros
Program:
#include <stdio.h>
//Function-like macros definition
#define multiply(a,b) (a*b);
int main()
{
int a = 20;
int b = 5;
int ans = multiply(a,b);
printf("20 multiply by 5 = %d", ans);
return (0);
}
Output:
20 multiply by 5 = 100
Predefined Macros in C language
__FILE__ expands to the full path to the current file.
__DATE__ expands to the current date.
__TIME__ used to get the current time.
__LINE__ contains the current line number in the source file.
__STDC__ used to confirm the compiler standard.