How to use C language macro definition

In C language, a macro definition is a preprocessing directive used to create aliases or constants for code. It uses #definekeywords 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 SQUAREmacro called which takes one argument xand 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_HELLOmacro called , which contains two lines of code. In the code, every time it is used PRINT_HELLO(), it is replaced with a two-line printfstatement.

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.

Guess you like

Origin blog.csdn.net/MyLovelyJay/article/details/133283348