function-macro
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| function-macro [February 17, 2026 at 21:49] – yanevskiv | function-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: | ||
| + | |||
| + | ```c | ||
| + | // Compile: gcc main.c -o program | ||
| + | // Run: | ||
| + | // Output: | ||
| + | #include < | ||
| + | #define sqr(x) ((x) * (x)) | ||
| + | |||
| + | int main() | ||
| + | { | ||
| + | printf(" | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | If want to make multiple statements in a function macro, a good way is to use `do { ... } while (0)`. This way, you gotta use ';' | ||
| + | ```c | ||
| + | // Compile: gcc main.c -o program | ||
| + | // Run: | ||
| + | // Output: | ||
| + | #include < | ||
| + | #define sqr_calc(expr) do { \ | ||
| + | int result = ((expr) * (expr)); | ||
| + | printf(" | ||
| + | if (result % 2 == 0) { \ | ||
| + | printf(" | ||
| + | } else { \ | ||
| + | printf(" | ||
| + | } \ | ||
| + | } while (0) | ||
| + | |||
| + | int main() | ||
| + | { | ||
| + | do_calc_sqr(2 + 3); | ||
| + | } | ||
| + | ``` | ||
| + | |||
| + | ## Links | ||
| + | |||
| + | - https:// | ||
| + | - https:// | ||
