Site Tools


function-macro

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
function-macro [February 17, 2026 at 22:02] yanevskivfunction-macro [May 14, 2026 at 11:38] (current) – external edit 127.0.0.1
Line 1: Line 1:
 +# 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))`.
 +
 +```c
 +// 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!
 +```c
 +// 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);
 +}
 +```
 +
 +## Links
 +
 + - https://stackoverflow.com/questions/15575485/function-like-macros-in-c
 + - https://www.geeksforgeeks.org/cpp/macros-vs-functions/