> ## Documentation Index
> Fetch the complete documentation index at: https://learn.acadlink.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Functional Macros

> Writing macros that behave like functions using #define

# Functional Macros in C

A **function-like macro** (also called a parameterised macro) accepts arguments and expands them inline — like a function, but done at the preprocessor stage before compilation. They are faster than function calls because there is no function call overhead.

***

## Syntax

```c theme={null}
#define MACRO_NAME(param1, param2) (expression)
```

Always wrap the entire expression and each parameter in parentheses to avoid operator precedence bugs.

***

## Examples

**Square of a number:**

```c theme={null}
#define SQUARE(x)  ((x) * (x))
```

**Maximum of two numbers:**

```c theme={null}
#define MAX(a, b)  ((a) > (b) ? (a) : (b))
```

**Minimum of two numbers:**

```c theme={null}
#define MIN(a, b)  ((a) < (b) ? (a) : (b))
```

**Absolute value:**

```c theme={null}
#define ABS(x)     ((x) < 0 ? -(x) : (x))
```

***

## Complete Program

```c theme={null}
#include <stdio.h>

#define SQUARE(x)   ((x) * (x))
#define MAX(a, b)   ((a) > (b) ? (a) : (b))
#define CUBE(x)     ((x) * (x) * (x))

int main() {
    int num = 5;

    printf("Square of %d  = %d\n", num, SQUARE(num));
    printf("Cube   of %d  = %d\n", num, CUBE(num));
    printf("Max(3, 7)     = %d\n", MAX(3, 7));

    return 0;
}
```

**Output:**

```
Square of 5  = 25
Cube   of 5  = 125
Max(3, 7)    = 7
```

***

## Why Parentheses Matter

Without parentheses around parameters, expressions involving operators can produce wrong results:

```c theme={null}
#define BAD_SQUARE(x)  x * x
// BAD_SQUARE(2 + 3) expands to: 2 + 3 * 2 + 3 = 11 (wrong!)

#define GOOD_SQUARE(x) ((x) * (x))
// GOOD_SQUARE(2 + 3) expands to: ((2+3) * (2+3)) = 25 (correct)
```

**Always parenthesise both the parameters and the full expression.**

***

## Macros vs Functions

|               | Functional Macro | Function             |
| ------------- | ---------------- | -------------------- |
| Processed by  | Preprocessor     | Compiler             |
| Type checking | None             | Yes                  |
| Speed         | Faster — inlined | Slight call overhead |
| Debugging     | Harder           | Easier               |
| Code size     | Larger           | Smaller              |
| Side effects  | Possible         | None                 |

**Use macros for short, frequently-called operations. Prefer `inline` functions in C99+ for type safety.**
