I have taken an undergrad course in programming Languages which covered C. However not that I have started working in a company in embedded systems, I see a plethora of macros being used regularly in C.
Please share some links from where I can learn more about macros.
I have K&R 2nd Ed, but I think their style is too terse. Something with more examples would be better for me.
A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).
In C, the macro is used to define any constant value or any variable with its value in the entire program that will be replaced by this macro name, where macro contains the set of code that will be called when the macro name is used in the program.
Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it's used. A function definition occurs only once regardless of how many times it's called.
To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.
In all honesty, you should limit your use of macros to very simple definitions nowadays.
In other words, don't waste your time crafting complex functions with macros.
They tended to have three main uses in the past:
simple definitions for the pre-compiler to use such as #define USE_DEBUG
and #ifdef USE_DEBUG
. These are, by and large, stil very valuable in portable code.
fast "inline" functions such as #define SQR(x) ((x) * (x))
which are now much more suited to real inline functions. The macro version have a number of problems, one of which is that i = 7; j = SQR(i++);
will not necessarily do what you expect.
pre-processor enumerations like #define OKAY 0
, #define ERR_NOMEM 1
and so on - these are better done as real enumerations - because the macro versions are basic substitutions, you tend not to get the symbols in debugging information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With