C Macros
Syntax
#define identifier tokens
Example
#include <stdio.h>
#define PI 3.14159265359
int main() {
float r = 5.0;
float circumference = 2 * PI * r;
printf( "Circumference of the circle is: %f\n", circumference);
return 0;
}
Output
The output of the above example will be:
Circumference of the circle is: 31.415927
Explanation
A macro is a fragment of code that is given a name. This name is then used as a replacement for the code when the macro is executed. In C, the #define
directive is used to define a macro.
Use
Macros are frequently used in C programming to perform repetitive tasks, to simplify code, and to make code more readable. They are often used to define constants, to create shorthand notation for commonly used expressions, and to perform simple computation.
Important Points
- A macro is defined using the
#define
directive, followed by the macro name and the replacement text. - Macros can be used to define constants, to create shorthand notation, and to perform simple computations.
- Macros are processed by the preprocessor before the code is compiled.
- Macros can be problematic because they can obscure the code and cause unexpected behavior.
- Macros should be used judiciously and only when necessary.
Summary
In C programming, macros are often used to simplify code and make it more readable. They are defined using the #define
directive and can be used to define constants, create shorthand notation, and perform simple computation. However, they can also be problematic and should be used judiciously. Understanding the syntax and appropriate use cases for macros can greatly enhance your programming abilities in C.