C MoreLesson 51Free preview
C Macros
This lesson is part of C · All levels
Summary
Macro is a text substitution performed by a preprocessor before compilation and written with #define. A simple object macro such as #define PI 3.14159, whereas a function macro uses parameters such as #define MAX(a,b) ((a) > (b)? (a): (b)). Because it's just a substitution of text, macros are vulnerable when an expression is not encapsulated or the argument has side effects.
Key points
- The preprocessor replaces the macro before compilation starts, so no variables or types are created.
- Wrap the entire macro result and every argument in the bracket so that the order of operations remains true.
- Avoid side-effect arguments such as MAX(i++, 5) as they can be evaluated more than once.
- Use enum, inline, or ordinary functions when possible because it is safer than macro.
- Macros are also used to include guard and conditional compilation with #ifdef.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.