# C Pointers, Static Storage, Array Decay & Tricky Output Patterns
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Programming & Data Structures
Canonical URL: https://gateandnet.com/exams/gate-cs/programming-and-ds/c-pointers-and-recursion-traces

> Precedence of * and ++, 2D array pointer arithmetic, static variables in recursion, and string literal traps.

## Essential C Pointer Identities

Given `int a[5] = {10, 20, 30, 40, 50};`:
- `a` decays to `&a[0]` of type `int *` (steps by `sizeof(int)` bytes).
- `&a` has type `int (*)[5]` (pointer to entire array of 5 ints — `&a + 1` jumps across **all 5 elements**!).

```c
#include <stdio.h>
int main() {
    int a[5] = {10, 20, 30, 40, 50};
    int *p = (int *)(&a + 1);
    printf("%d %d\n", *(a + 1), *(p - 1));
    // Output: 20 50
    return 0;
}
```

## Static Variables Inside Recursive Functions

> [!TRAP]
> A `static` local variable has **single storage across all recursive activation frames**! If a return expression reads the `static` variable *after* a recursive call returns, use the **final post-unwinding value** of that static variable!

```c
int f(int n) {
    static int r = 0;
    if (n <= 0) return 1;
    if (n > 3) {
        r = n;
        return f(n - 2) + 2;
    }
    return f(n - 1) + r;
}
// Trace f(5): sets r = 5 -> calls f(3) -> f(2) -> f(1) -> f(0)=1
// Unwinding adds r (=5) three times, then +2: 1 + 5 + 5 + 5 + 2 = 18!
```


## Solved Practice Questions & PYQs

### [GATE CS C Trace | NAT]
What integer value is returned by calling `f(5)` for the C function `int f(int n) { static int r = 0; if (n <= 0) return 1; if (n > 3) { r = n; return f(n - 2) + 2; } return f(n - 1) + r; }`?
**Correct Answer:** 18
**Solution:** `f(5)` sets static `r = 5` and evaluates `f(3) + 2`. Then `f(3) -> f(2)+r -> f(1)+r+r -> f(0)+r+r+r`. Since `r = 5` persists in static storage, `1 + 5 + 5 + 5 + 2 = 18`.
