eolas/zk/Macros_in_C.md
2025-12-17 18:22:42 +00:00

38 lines
745 B
Markdown

---
tags:
- C
---
Think of them as a find and replace that takes place before compilation.
They are ephemeral and never make it into the compiled code.
With a macro, the computation happens "inline" without having to call functions
which make costly alterations to the stack.
A function and function call such as:
```c
int square(int x) { return x * x; }
int a = square(5);
```
Can be reduced to a macro:
```c
#define SQUARE(x) ((x) * (x))
int a = SQUARE(5);
```
Which, because it uses `#` is processed at the
[pre-processor compilation stage](./C_compilation_process.md), becomes:
```c
int a = ((5) * (5));
```
after pre-processing but before compilation.
## Syntax
`#define` always creates a macro but there are different types.