In C language, a macro definition is a preprocessing directive used to create aliases or constants for code. It uses #define
keywords to define macros.
Here's how to use macro definitions:
1) Simple macro definition:
#define PI 3.14159
This will define a macro called PI for the value 3.14159. In the code, every occurrence of PI will be replaced with 3.14159.
2) Macro definition with parameters
#define SQUARE(x) ((x) * (x))
This will define a SQUARE
macro called which takes one argument x
and replaces it in code ((x) * (x))
. Whenever used in code SQUARE(y)
, it will be replaced by ((y) * (y))
.
3) Multi-line macro definition
#define PRINT_HELLO() \ printf("Hello, "); \ printf("world!\n");
This will define a PRINT_HELLO
macro called , which contains two lines of code. In the code, every time it is used PRINT_HELLO()
, it is replaced with a two-line printf
statement.
Note that in macro definitions, trailing parentheses or semicolons are usually required to avoid syntax errors.
These are the basic uses of macro definitions. By using macro definitions, you can create aliases, constants, or simple functions for your code to make your code more readable and maintainable.