Introduction to Macros in C

Google+ Pinterest LinkedIn Tumblr +


Almost everyone already defined a constant in C using

#define CONST 12345

but only a small group really knows what that line does and how to explore these features. Every line that starts with a # is not processed by the C compiler, but by the C pre processor that parses these lines and produces the code that will effectively be compiled. In gcc, you can see the result of the preprocessing stage using gcc -E src.c

What the define directive does is make the preprocessor replace EVERY occurrence of the definition by the text that follows it. The replacement is purely textual and there are a few tricks that are really awesome. I’ll talk about two of them: function-like macros and multi line macros.

Function-like macros

To make a function-like macro just put the usual parenthesis after the name of the macro and follow the name of its arguments. The arguments will be replaced by the EXACT string that you pass to the macro. A quick example

#define print_int(x) printf(“Int %d\n”, x);

When called print_int(30), the macro will expand to

printf(“Int %d\n”, 30);

Multiline macros

A multiline macro can be built putting a \ in the end of all the line of the macro. This character indicate that the macro continues on the next line.

#define SWAP(a, b) { \
a ^= b; \
b ^= a; \
a ^= b; \
}

The parenthesis are required because that block needs to be evaluated as a single instruction. Without it, the following would fail:

if (a > b) SWAP(a, b)

Macros are dangerous

Macros produces errors that are difficult to debug and tricky to patch. The possible traps are many (errors in the precedence of operators, self-referencing macros, etc). This page have all of them really well documented.

This was a little introduction to a more advanced use of C macros. The preprocessor is a powerful feature and can be used to make lots of good stuff. To know more about it one can visit this site.

Share.

About Author

Leave A Reply