C Macros
C Macros
#define
#define
defines a variable to a value (or nothing if it's not defined). It
is a literal find and replace kinda stuff, so be aware of what's happening
after rewrites. It can also be used in a functional fashion and has a bunch
of operators.
#define macro_name([parameter_list]) replacement_text
will use it as a
function. Once again, keep in mind that it's a literal find and replace.
#define square(x) x*x int main() { int y = square(3+2); }
This would actually give 11
as if it's 3 + 2*3 + 2
.
Variadic Macros
There are also variadic macros that take in multiple arguments.
#define ARGS(x, ...) do {\ printf("%d\n", ##__VA_ARGS__); \ } while (0)
A common trick is to wrap a macro in a do-while loop as that eliminates issues with using semicolons and otherwise. We can also convert the arguments to a string in a macro by using #arg wherever we need it. To evaluate a macro result as a string, we need two macros
#define xstr(s) str(s) #define str(s) #s #define foo 4 str (foo)
→ "foo" xstr (foo) → xstr (4) → str (4) → "4"
s
is stringized when used in str
so not macro expanded first. but for xstr
it is an ordinary argument so it is macro expanded before xstr
itself is
expanded. See here why.
Similarly, there is ##
that is used for concatenation of two items in a
macro. This is very often used to concatenate the arguments. Like the
stringizing macro, this needs to be redirected to another macro for
evaluation.