Table of Contents
Function macro
Function macro is a C preprocessor macro that looks like a function call when you use it.
This is a basic example with a single expression. sqr(x) looks and feels like a function even though it's a macro. A good habit to get into is to always enclose arguments into parenthesis when you define function macros. For example, #define sqr(x) x * x would not behave like you would expect: sqr(2 + 3) would expand into 2 + 3 * 2 + 3 which results in 11, not 25. By enclosing the arguments in parenthesis you guarantee precedence ((2 + 3) * (2 + 3)).
// Compile: gcc main.c -o program // Run: ./program // Output: Square of five is 25 #include <stdio.h> #define sqr(x) ((x) * (x)) int main() { printf("Square of five is %d\n", sqr(2 + 3)); }
If want to make multiple statements in a function macro, a good way is to use do { ... } while (0). This way, you gotta use ';' like you do when you call an actual function. Just remember to use '\' to extend the macro across multiple lines!
// Compile: gcc main.c -o program // Run: ./program // Output: Square of '2 + 3' is 25! #include <stdio.h> #define sqr_calc(expr) do { \ int result = ((expr) * (expr)); \ printf("Square of '" #expr "' is %d! ", result); \ if (result % 2 == 0) { \ printf("%d is an odd number", result); \ } else { \ printf("%d is an even number", result); \ } \ } while (0) int main() { do_calc_sqr(2 + 3); }
