macros in c
What is Macros in c?
In C programming language, a macro is a preprocessor directive that is used to define a symbolic name or a sequence of code that can be replaced with another sequence of code during the compilation process. Macros are defined using the #define directive and are typically used to simplify repetitive or complex code, to define constants, or to provide conditional compilation.
Micros are a small part of the program which is replaced with another part of the preprocessor unit
Macros is two type
- Predefined macros
- user-defined Macros(without arguments, with arguments)
Example of micros
#include
#define PF printf
void main()
{
PF("hello electro4u.net\n");
}
Output: hello electro4u.net
Attention: here we can define one macro PF with respect of printf, so that why we can use the PF as prinf for printing the output
Example: Program 2
#include<stdio.h>
#define int char
void main()
{
int i;
#undef int
int j;
printf("%ld\n",sizeof(i));
printf("%ld\n",sizeof(j));
}
Note: micros name not should be constant
What is the benefit of macros
- Readability
- Replacement becomes easy
Predefined macros:
all the predefined macros start with a double underscore and end with a double underscore (_ _)
Program:
#include
void main()
{
printf("%s\n",__FILE__);
printf("%d\n",__LINE__);
printf("%s\n",__DATE__);
printf("%s\n",__TIME__);
}
Output:
5
Dec 28 2022
13:13:53
user-defined Macros(without arguments, with arguments)
Macro without Arguments:
This type of macro doesn't take any arguments and is simply a substitution of one string for another.
Example:
#define PI 3.14159
In this example, whenever the preprocessor encounters PI in the code, it will replace it with 3.14159.
Macro with Arguments:
This type of macro can accept one or more arguments and can perform operations on those arguments before substituting them into the code.
Example:
#define SQUARE(x) ((x) * (x))
In this example, SQUARE(x) is a macro that takes one argument (x) and returns the square of x.
Usage:
int result = SQUARE(5); // This will be replaced with: int result = ((5) * (5));
After preprocessing, this becomes:
int result = 25;
Note: Be cautious with macros that take arguments, as they can sometimes lead to unexpected behavior due to the way they are substituted in the code. For example, SQUARE(x++) would not behave as expected.