Macros
You should always use capital letters for macro functions and there are no spaces in names and its limited to one line only.
Example:
Macros vs functions
All macros are preprocessed which means all of them would be processed before your program compiles.
Functions are not preprocessed, they are compiled.
A macro is always faster than a function, functions take longer than inline code (macros for example).
For one time use a macro is not really a big deal but a macro inside a nested loop is a much better candidate for speed improvements.
We can use profilers to determine where a program spends the most time.
When calling a function it has to locate some data (a newly allocated stack frame).
Macros don't have this overhead. Macros insert directly into the program (textual program) so if we use the same macro 20 times we get 20 lines of code added into our program.
Functions are preferred over macros when writing large chunks of code.
With macros you don't have to worry about variable types.
Functions give us type checking. If a function expects a string but you give it an int, you will get an error.
Debugging a macro is much harder than debugging a function. A function can be stopped through by the debugger but a macro cannot.
Alternatives
Inline functions are the best alternative to macros.
When we add the inline keyword in front of the function it hints the compiler to embed the function body inside the caller (just like a macro).
Inline functions can be debugged and also have type checks.
However the inline keyword is just a hint and not a strict rule.
Creating macros
There are 2 ways of defining macros:
1. Symbolic constants (constants represented as symbols).
2. Function macros (operations defined as symbols).
Symbolic constants
Example:
Defines a macro and some replacement text. after definition the macro can be used as follows:
Leading or trailing white space around the replacement text is discarded.
Example:
Function macros
Example:
Defines a macro and some replacement text.
The list of identifiers separated by commas appears between parentheses following the macro_name(FMAC).
Each identifier can apear one or more times in the substitution string.
Using:
Example:
Output:
Macros with arguments
Example:
Standard C pre-defined macros
Last updated