What are the rules for defining macros in C?
The rules for defining macros in the C language are as follows:
- A macro definition is defined using the #define keyword, with the format: #define macro_name replacement_text.
- An identifier in C language consists of letters, numbers, and underscores, cannot begin with a number, and should not have the same name as a C language keyword.
- Substitution text is the content that replaces a macro name when it appears in a program.
- A macro definition is typically placed at the beginning of a source code and can be used anywhere within the code.
- A macro definition is a simple text replacement without type checking, syntax checking, or scope restrictions. It cannot define macros with multiple lines.
- There is no need to add a semicolon after a macro name, as macro definitions are not C statements and do not require a semicolon at the end.
- Macro definitions can be nested, but be careful not to nest too deeply in order to avoid creating difficult-to-maintain code.
- In macro definitions, parameters can be used and enclosed in parentheses. Multiple parameters are separated by commas and can be used in the replacement text.
- Be cautious when using parameters in macro definitions as they are typeless, to prevent unexpected outcomes.
- The replacement text in a macro definition can include predefined macros such as __FILE__, __LINE__, etc.
- Conditional compilation statements can be used in macros, such as #if, #ifdef, etc.
- Macro definitions can be cancelled by using the #undef keyword.
It is important to note that macro definitions perform text replacement in the preprocessing stage, so the replacement of macros is a simple text replacement and does not involve calculations or evaluations. When using macro definitions, be cautious to avoid unexpected replacement results.