C · whole subject on one page

Short notes: C Programming

Every topic in revision form: the key ideas, formulas, the question types GATE asks, and the traps. Read it the night before.

1. 🔢 Types, Operators & Expressions

High yield ●●●2 PYQs →

Every output question depends on exact integer behaviour: wrap-around, integer division, precedence, side effects, and bitwise tricks.

  • Integer types, ranges and overflow. On a typical machine char = 1, short = 2, int = 4, long = 8 bytes. An n-bit signed type holds −2n−1 … 2n−1−1, an unsigned one 0 … 2n−1. Unsigned arithmetic wraps modulo 2n; signed overflow is undefined behaviour (in practice it wraps, but the exam may call it undefined).
    → n bits: wrap modulo 2n; unsigned is always defined, signed overflow is undefined.
  • Operators, precedence and associativity. Order of tightness: postfix ( ) [ ] ++ --, then unary ! ~ - * & ++ -- sizeof, then * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, ?:, assignment, comma. Most binary operators are left-to-right; assignment, ?: and unary operators are right-to-left. Precedence tells you the grouping, not the order of evaluation.
    → Precedence = grouping, not order of evaluation. Bitwise & ^ | sit below ==.
  • Increment, decrement and side effects. x++ gives the old value and then adds 1; ++x adds 1 and gives the new value. Changing the same variable twice, or reading it while changing it, between two sequence points (as in i = i++ + ++i or a[i] = i++) is undefined behaviour. Sequence points exist at ;, &&, ||, ?:, the comma operator and before a function call.
    → x++ yields the old value, ++x the new one; twice in one expression is undefined.
  • Bitwise operators and shifts. & | ^ ~ act on every bit; x << k multiplies by 2k, x >> k divides by 2k (rounding toward −∞ for negative signed values in practice). Useful tricks: x & (x−1) clears the lowest 1 bit, x & −x isolates it, x & 1 tests odd, x ^ x = 0. & is not &&, and ^ is XOR, not power.
    → & keeps common 1s, | merges, ^ marks differences; x & (x−1) clears the lowest 1 bit.
  • Type conversion, casts and integer division. In a mixed expression both operands are converted to the "bigger" type (the usual arithmetic conversions); char and short first become int. If one operand is unsigned and the other signed of the same size, the signed one becomes unsigned, so -1 < 1u is false. Integer division truncates toward zero (−7/2 = −3, −7%2 = −1). Assigning a double to an int drops the fraction.
    → Mixed types: promote, then compute. Integer division truncates toward 0; signed + unsigned means unsigned.

Formulas

Signed n-bit range
−2^(n−1) … 2^(n−1) − 1 (int: −2147483648 … 2147483647)
Unsigned n-bit range
0 … 2^n − 1 (unsigned int max 4294967295)
Unsigned wrap
result = value mod 2^n (so (unsigned)−1 = 2^32 − 1)
Shifts
x << k = x · 2^k x >> k = ⌊x / 2^k⌋
Clear lowest set bit
x & (x − 1) isolate it: x & (−x)
Division and remainder
a == (a / b) * b + a % b, with / truncating toward 0
Masks
n low ones = (1 << n) − 1

What GATE asks

  • ★★★Bitwise operators on characters or integers. Apply & | ^ to ASCII codes, then add or subtract and print as a char.
  • ★★★Loop with integer division or overflow. Does the loop terminate? Does x = x + x + y exceed a power of two?
  • ★★★Unsigned subtraction in a comparison. strlen(a) − strlen(b) is unsigned and never negative.

Traps

strlen and sizeof return unsigned: strlen(a) - strlen(b) > 0 is true whenever a ≠ b in length.
Precedence of & versus ==: x & 1 == 0 means x & (1 == 0).
5/2 = 2 but 5/2.0 = 2.5; and 1/2*4 = 0.
Superscripts in exam text matter: 220 and 220 are different numbers.

2. 🔀 Control Flow & Output

High yield ●●●10 PYQs →

Tracing a loop, a switch without break, or a short-circuited condition by hand is the core skill behind most C output questions.

  • if/else and the three loops. while tests first, do-while runs the body at least once, and for(init; cond; step) is a while loop with the step run after the body. break leaves the nearest loop or switch; continue jumps to the next test (to the step in a for loop). A semicolon right after if (...) or for (...) makes the body empty.
    → Test, body, step, repeat; the step runs after the body; break skips the step.
  • switch and fall-through. A switch jumps to the matching case label and then keeps running every following statement, through later labels and the default, until a break (or the closing brace). Labels must be integer constants and may be grouped. The default label can appear anywhere.
    → Switch enters at the match and falls through until a break.
  • Short-circuit evaluation and ?:. a && b does not evaluate b when a is 0; a || b does not evaluate b when a is non-zero. Side effects in b (such as i++) may never happen. The result is always 0 or 1. c ? x : y evaluates only one branch. The comma operator evaluates left to right and gives the last value.
    → && and || skip the right operand when the left decides the answer.
  • printf, return values and format specifiers. %d int, %u unsigned, %ld long, %c char, %s string, %f double (6 decimals), %x hex, %% a percent sign. printf returns the number of characters printed. printf("%d", x) with a missing or mismatched argument is undefined behaviour. Output questions often depend on exactly where \n appears.
    → printf prints exactly what the format says and returns the character count.

Formulas

Iterations of for(i=a; i<b; i+=s)
⌈(b − a) / s⌉ (when b > a, s > 0)
Halving loop for(i=n; i>1; i/=2)
⌊log₂ n⌋ iterations
Doubling loop for(j=1; j<n; j*=2)
⌈log₂ n⌉ iterations
Nested loops, inner depends on outer
sum the inner counts: Σ over i of (inner count)
Triple loop i ≤ j < k ≤ n
C(n+1, 3) = (n−1)·n·(n+1) / 6
Switch fall-through
output = every statement from the matched label to the first break

What GATE asks

  • ★★★Trace a loop with integer or short-circuit side effects. Keep a table of the variables after each iteration; watch out for i++ inside &&.
  • ★★★How many times is a statement executed?. Count iterations of nested loops or fork-style repeats.
  • ★★★Does this loop terminate?. Look at whether the loop variable can reach the exit value (for example integer division stuck at 1).

Traps

if (x = 5) assigns, then tests 5 (true).
A for loop step runs before the next test, so after a break the step has not run.
In if ((j >= 0) && (i++)) i is incremented only when j ≥ 0.
A switch with no break prints all later cases.

3. 👉 Pointers & Arrays

High yield ●●●11 PYQs →

The most frequent C topic in GATE. You must read *p++, a[i], *(a+i), p[1] and pointer differences without hesitation.

  • Pointers: address, dereference, aliasing. A pointer variable holds an address. &x is the address of x and *p is the object p points to. Two pointers to the same object are aliases: writing through one changes what the other reads. *p++ means *(p++) (use the old pointer, then advance), whereas (*p)++ increments the pointed-to value. A NULL pointer must never be dereferenced.
    → & = address, * = follow it; *p++ moves the pointer, (*p)++ changes the value.
  • Pointer arithmetic. p + k moves by k elements, not k bytes: the address changes by k · sizeof(*p). p − q (same array) gives the number of elements between them, of type ptrdiff_t. You can compare pointers into one array, and p[i] is exactly *(p + i), so i[p] also works. Adding two pointers is illegal.
    → p + k moves k elements; p − q counts elements; a[i] ≡ *(a + i).
  • Arrays, decay and sizeof. In most expressions an array name decays to a pointer to its first element, so a, &a[0] and a + 0 are the same address. Exceptions: sizeof a gives the whole array size, and &a is a pointer to the whole array (so &a + 1 jumps past it). An array parameter is really a pointer, so inside the function sizeof gives 8, not the array size. Arrays cannot be assigned.
    → a decays to &a[0]; sizeof(a) is the whole array; a parameter array is a pointer.
  • Two-dimensional arrays (row-major). int a[R][C] is R arrays of C ints stored row after row: the address of a[i][j] is base + (i·C + j)·sizeof(int). a decays to a pointer to a row (int (*)[C]), so a + i skips whole rows, *(a + i) is row i, and *(*(a + i) + j) is a[i][j]. Initialisers may omit inner braces: they fill in row-major order.
    → a[i][j] ≡ *(*(a + i) + j) at offset (i·C + j) elements; a + 1 skips a row.
  • Pointers to pointers. A char ** holds the address of a char *. A function that must change the caller's pointer takes a pointer to it, as in swap(char **a, char **b). Swapping two local copies of pointers does nothing in the caller. argv is a char ** (array of strings).
    → To modify a pointer in the caller, pass the pointer's address (T **).

Formulas

Address of a[i]
base + i · sizeof(a[0])
Address of a[i][j] in int a[R][C]
base + (i·C + j) · sizeof(int)
Pointer difference
(p − q) = (address(p) − address(q)) / sizeof(*p)
Array and pointer equivalences
a[i] ≡ *(a + i) &a[i] ≡ a + i
sizeof
sizeof(int a[10]) = 40 bytes, but sizeof of an int* parameter = 8
2-D access
a[i][j] ≡ *(*(a + i) + j) ≡ *(a[i] + j)

What GATE asks

  • ★★★Output of a pointer/array program. Draw the array, mark each pointer with an arrow, update on every statement (*p++, (*p)++, p[1]).
  • ★★★2-D / 3-D array indexing with a pointer expression. Convert to row-major offsets: *(*(a + i) + j).
  • ★★★Swap functions: value vs pointer vs pointer-to-pointer. Decide which copy is changed: only a **pointer to the pointer** changes the caller's pointer.
  • ★★★Page faults or cache misses from array traversal order. Row-major layout: walking down a column touches a new page or block each time.

Traps

*p++ is *(p++), not (*p)++.
p + 1 adds sizeof(*p) bytes.
sizeof of an array parameter is the size of a pointer.
A 3-D initialiser with fewer braces is filled in row-major order, not row by row.

4. 🔤 Strings & Characters

Medium ●●3 PYQs →

String loops with pointers, the null terminator and unsigned size_t pitfalls appear regularly as short output questions.

  • Strings, the null terminator and arrays vs literals. A C string is a char array ending in '\0'. char s[] = "abc" is a modifiable array of 4 chars. char *s = "abc" points to a read-only literal: writing through it is undefined. sizeof("abc") = 4 but strlen("abc") = 3. The terminator is not counted by strlen but must fit in the array.
    → String = chars + '\0'; sizeof counts the terminator, strlen does not.
  • Library functions and pointer loops. strlen counts up to the terminator, strcpy copies including it, strcmp returns 0 for equal strings (negative or positive otherwise, not exactly −1 or 1), strcat appends. The classic copy loop is while (*t) *s++ = *t++;. If the loop stops before copying the terminator, the destination keeps its old tail, as in the 2025 question that printed "Hello World!d!".
    → The loop test decides whether '\0' is copied; leftover characters stay as they were.
  • Characters as integers and size_t pitfalls. A char is a small integer: 'A' = 65, 'a' = 97, '0' = 48, so 'a' − 'A' = 32 and c − '0' converts a digit. Arithmetic and bitwise operators on chars first promote them to int. strlen and sizeof give size_t, an unsigned type, so strlen(a) − strlen(b) never goes negative: it wraps to a huge positive number.
    → chars are ints; strlen and sizeof are unsigned, so never subtract them blindly.

Formulas

Storage for a string of n characters
n + 1 bytes (terminator)
sizeof vs strlen
sizeof("abc") = 4, strlen("abc") = 3
ASCII anchors
'0' = 48, 'A' = 65, 'a' = 97, so 'a' − 'A' = 32
Digit to value
c − '0'
strlen(a) − strlen(b)
unsigned: wraps modulo 2^64 when negative

What GATE asks

  • ★★★What does this string loop print?. Simulate pointer s and t over the array; remember whether the terminator was copied.
  • ★★★Return value of a pointer-difference string function. b − a after advancing b to the terminator gives strlen(a).
  • ★★★Unsigned arithmetic with strlen. Compare lengths directly instead of subtracting.

Traps

Forgetting the +1 for the null terminator.
Modifying a string literal is undefined.
if (strcmp(a,b)) is true when the strings are different.
sizeof on a char * gives 8, not the string length.

5. 🔁 Functions & Recursion

High yield ●●●11 PYQs →

Recursive output and "how many calls" questions are standard, and parameter passing (by value only) is a favourite trap.

  • Functions and call by value. C passes every argument by value: the function gets a copy, so assigning to a parameter never changes the caller's variable. A function needs a prototype or definition before use. A non-void function that reaches its end without return gives an undefined value.
    → Arguments are copies; assigning to a parameter never touches the caller.
  • Call by reference with pointers. To let a function change the caller's variable pass its address and write through it: void foo(int *p, int x) { *p = x; }. The pointer itself is still passed by value, so reassigning p inside the function is invisible outside, while *p = … is visible. Arrays are passed as a pointer to the first element, so changes to elements are visible.
    → *p = … reaches the caller; p = … does not. Arrays are passed by address.
  • Recursion and the call stack. A recursive function needs a base case and a step toward it. Each call gets its own activation record (parameters, locals, return address) on the stack; the calls unwind in last-in-first-out order. Work done before the recursive call happens in call order, work after it happens on the way back, which reverses the order (printing digits after the call prints them reversed).
    → Before the call = call order, after the call = reverse order; always find the base case.
  • Tracing recursion: counting calls and return values. Write the calls as a tree. For a linear recursion on n the depth is n. For f(n) = f(n−1) + f(n−2) the number of calls is exponential (Fibonacci-like): calls(n) = calls(n−1) + calls(n−2) + 1. A recursion that does not shrink its argument (such as foo(val--), which passes the old value) never reaches the base case and ends in stack overflow.
    → Draw the call tree; count nodes; check the argument really shrinks.
  • Argument evaluation order and return values. The order in which the arguments of a call are evaluated is unspecified: f(g(10), h(20)) may call g first or h first. The exam states the assumption (for example "right to left"). The comma between arguments is not the comma operator. Functions return by value; returning the address of a local variable is undefined.
    → Argument evaluation order is unspecified; obey the order the question states.

Formulas

Depth of linear recursion f(n−1)
n + 1 frames (including the base case)
Calls for f(n) = f(n−1) + f(n−2)
C(n) = C(n−1) + C(n−2) + 1, C(0) = C(1) = 1
Binary recursion halving n
calls = O(log n) with one branch, O(n) with two
Stack space of recursion
depth × size of one frame
Horner loop total = x·total + a[i]
evaluates the polynomial; with x = 2 and all a[i] = 1 gives 2^n − 1

What GATE asks

  • ★★★Output of a recursive function (print before/after the call). Draw the call tree and keep the printing order for before-call and after-call statements.
  • ★★★Value returned by a recursive function on an array. foo(S+1, size−1) walks the array one element at a time; track what each call adds.
  • ★★★Pass by value vs pointer. Mark which variables are copies and which are written through an address.
  • ★★★Evaluation order of arguments. Follow the question's stated order (right to left) and print as each function runs.

Traps

Arguments are copies; only *p = … changes the caller.
foo(val--) passes the old value, so the recursion never shrinks.
A function printing after the recursive call prints in reverse order.
The order of evaluation of arguments is unspecified unless the question says otherwise.

6. 🧠 Storage Classes, Scope & Memory

High yield ●●●8 PYQs →

static variables and scope are a favourite way to make a short program tricky; memory-layout questions also overlap with OS and compilers.

  • Storage classes: auto, register, static, extern. auto (the default for locals): created on entry to the block, destroyed on exit, new value every call. register: a hint to use a CPU register (you cannot take its address). static local: created once, initialised once (to 0 by default), and keeps its value between calls. extern: declares a global defined elsewhere. A static global is visible only in its own file.
    → static = one copy, initialised once, value persists; auto = fresh on every call.
  • Scope and shadowing. A variable is visible from its declaration to the end of its block. An inner declaration with the same name shadows the outer one, and the outer value is untouched. Globals are visible everywhere after their declaration. C uses static (lexical) scoping: a name refers to the nearest enclosing declaration in the program text, never to the caller's locals.
    → Names resolve to the nearest enclosing declaration in the program text.
  • Memory layout of a C program. Low to high addresses: code (text), initialised data, uninitialised data (BSS, zeroed), then the heap (grows up, malloc) and the stack (grows down, locals). Globals and static variables live in data/BSS; locals and parameters live on the stack; malloc'd memory lives on the heap and stays until free.
    → Stack = locals; heap = malloc; data/BSS = globals and statics; code = instructions.
  • Stack frames (activation records). Each call pushes a frame holding the parameters, the return address, the saved frame pointer and the local variables; returning pops it. Frames of the caller stay below. Deep or infinite recursion exhausts the stack (stack overflow). Static and global variables are not in the frame, which is why they survive across calls.
    → A frame = parameters + return address + locals; recursion stacks one frame per call.
  • Dynamic memory: malloc, free, leaks and dangling pointers. malloc(n) returns n bytes of heap memory (or NULL) that you must free. Memory leak: you lose the only pointer to a block (for example by overwriting it) before freeing it. Dangling pointer: you use a pointer after free, or after the stack frame it points into has been popped. Double free and writing past the block are undefined behaviour. malloc needs no cast in C.
    → Lost pointer to a live block = leak; pointer to freed or dead memory = dangling.

Formulas

static local
initialised once; lifetime = whole program; scope = its block
Default values
static and global: 0; auto: indeterminate (garbage)
Where does it live?
local → stack; malloc → heap; global/static → data or BSS; code → text
Frame contents
parameters + return address + saved registers + locals
Leak vs dangling
leak = lost pointer, block never freed; dangling = pointer to freed or dead memory

What GATE asks

  • ★★★Value printed by a program with static counters. Keep the static variable in its own column and update it across calls.
  • ★★★Shadowing of globals and locals. Match each name to the nearest declaration; blocks create new variables.
  • ★★★What problem does this malloc code have?. Look for a pointer overwritten before free (leak) or used after free (dangling).

Traps

A static local is initialised only once, not on every call.
Inside a block, static int a = 1; in main and a global a are different variables.
register and auto locals reset on each call.
Returning the address of a local gives a dangling pointer.

7. 🧱 Structs, Unions & Undefined Behaviour

Medium ●●2 PYQs →

Layout and sizeof questions test your model of memory; the undefined-behaviour checklist lets you answer "what will this program print?" correctly when the answer is "anything".

  • Structs: layout and member access. A struct stores its members one after another in declaration order. The address of a member is the struct base plus its offset. s.x uses the object, p->x uses a pointer (the same as (*p).x). Structs can be copied and passed by value (the whole struct is copied). An array member makes the struct large: struct data { int marks[100]; char grade; int cnumber; } has grade at offset 400.
    → Offset = bytes of everything before the member (plus padding).
  • Padding, alignment and sizeof. Each member is aligned to its own size (an int at a multiple of 4, a double at a multiple of 8) and the struct size is rounded up to a multiple of the largest alignment. The compiler inserts padding bytes to achieve this, so sizeof(struct) can be larger than the sum of the members. Putting large members first usually wastes less space. Packed structs remove padding.
    → Align each member to its size, round the total up to the largest alignment.
  • Unions, enums and typedef. All members of a union share the same memory, which is as large as its biggest member (rounded up for alignment); only the last member written has a meaningful value. An enum is a set of named int constants starting at 0 unless set. typedef gives an existing type a new name, for example typedef struct node node;.
    → Union size = largest member; members share storage.
  • Undefined, unspecified and implementation-defined behaviour. Undefined: anything may happen. Examples: signed overflow, null or dangling dereference, out-of-bounds access, modifying a variable twice between sequence points (i = i++ + ++i), reading an uninitialised local, a printf format that does not match its argument, shifting by too many bits. Unspecified: argument evaluation order. Implementation-defined: the size of int, the result of right-shifting a negative number.
    → Undefined = no guarantee at all; unsigned wrap and integer truncation are fully defined.

Formulas

Struct size
sum of members + padding, rounded up to a multiple of the largest member alignment
Offset of a member
round the running offset up to the member's alignment
Union size
size of the largest member (rounded up to the largest alignment)
p->x
(*p).x
Array of structs
element i is at base + i · sizeof(struct)

What GATE asks

  • ★★★Offset of a struct field (addressing mode). Add up the sizes of the earlier members to get the displacement.
  • ★★★Output through a char* cast of a struct pointer. Treat the struct as consecutive bytes; (char*)q + 1 is the second char member.
  • ★★★Which statements about undefined behaviour are true?. Check each statement against the undefined-behaviour list.

Traps

sizeof(struct) is often larger than the sum of its members.
A union stores one value at a time.
Reading a different union member than the one last written is not portable.
An uninitialised local is garbage, not 0.