What are the rules for defining macros in C?

The rules for defining macros in the C language are as follows:

  1. A macro definition is defined using the #define keyword, with the format: #define macro_name replacement_text.
  2. 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.
  3. Substitution text is the content that replaces a macro name when it appears in a program.
  4. A macro definition is typically placed at the beginning of a source code and can be used anywhere within the code.
  5. A macro definition is a simple text replacement without type checking, syntax checking, or scope restrictions. It cannot define macros with multiple lines.
  6. 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.
  7. Macro definitions can be nested, but be careful not to nest too deeply in order to avoid creating difficult-to-maintain code.
  8. 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.
  9. Be cautious when using parameters in macro definitions as they are typeless, to prevent unexpected outcomes.
  10. The replacement text in a macro definition can include predefined macros such as __FILE__, __LINE__, etc.
  11. Conditional compilation statements can be used in macros, such as #if, #ifdef, etc.
  12. 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.

bannerAds