Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 4: Control Flow, Stdlib, Undefined Behaviour & Gotchas
C

Part 4: Control Flow, Stdlib, Undefined Behaviour & Gotchas

Review control flow, standard library functions, I/O, recursion, undefined behavior, and tricky C programming pitfalls.

1. Control flow — decisions & loops

  • if/else, ternary ? :, switch (falls through unless break), for/while/do-while.
  • switch on int/enum; duplicate/literal cases are a compile error; default clause is optional.
  • do while runs the block first, then checks the condition at least once.
  • goto exists — used for cleanup in C and some kernels only.

Classic output trap: break only exits the current switch/loop; falling through a case without break continues executing the next case.

2. Recursion — the placement favorite

int fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }

Hazards to flag quickly in interviews:

  • Base case missing = infinite recursion → stack overflow.
  • Fibonacci naive is exponential — memoise with an array.
  • Tail recursion in C is not guaranteed optimized.

3. I/O and stdlib — the standard toolkit

  • printf/scanf family: %d, %f, %c, %s, %p, %x, %zu (size_t); %s prints from a char* until \0.
  • Format-string mismatch == UB, often the first out-of-range diagnosis (%f printing int etc.).
  • exit() vs _exit(); atoi/strtol (strtol usually better error handling).
  • qsort/bsearch with comparator functions on const void *.
int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; }
qsort(arr, n, sizeof(int), cmp);

4. Undefined behaviour — the top-5 interview list

  1. Dereference NULL / wild pointers.
  2. Out-of-bounds array access (read or write).
  3. Use of a dangling pointer (after free / after stack frame ends).
  4. Signed integer overflow (INT_MAX + 1).
  5. Shifting by >= width of the type.

Some look “normal” but are UB: bad printf format, strcpy overflow, modifying a string literal, reading uninitialized data.

5. The gotcha sheet

  • sizeof computed at compile time — not a function; sizeof(array) vs sizeof(pointer).
  • Integer division truncates toward zero in C99+: 7/2 == 3.
  • Ternary type promotion surprises.
  • Comma in expression vs function-arg list: a, b vs f(a, b).
  • && || short-circuit — the right operand side doesn’t run when result is known.
  • static local: initialized once, persists across calls.
  • unsigned arithmetic wraps fast; mixing signed/unsigned is a minefield.

6. Interview checkpoint

  • Recursion base/hazards; stack depth.
  • printf/scanf format correctness — %zu, %p, %x.
  • Spotting UB: run UBSan/valgrind to confirm your candidate list.
  • The gotcha sheet above — say it once, cleanly.

My Private Notes

Notes are auto-saved locally to this device.