Skip to content
GATEiit

GATE CSE · Programming and Data Structures

Programming in C

The C that GATE tests through output questions: operators and precedence, integer arithmetic, control flow and macros, pointers, arrays and strings, parameter passing, scope and storage classes.

Before you start

  • Binary representation of integers

    Integer overflow, signed and unsigned comparison and bit operators depend on how ints are stored.

  • Memory addresses →

    Pointers are addresses; pointer arithmetic is address arithmetic scaled by the element size.

This topic comes before: Arrays, stacks, queues and linked lists, Instruction set and addressing modes, Inter-process communication, concurrency and synchronization, Recursion, Runtime environments, System calls, processes and threads

Concept notes

1. Operators, precedence and integer arithmetic

Integer division truncates towards zero (C99 onwards): 7 / 2 is 3 and -7 / 2 is −3. The remainder has the sign of the dividend: -7 % 2 is −1. It always holds that (a / b) * b + a % b == a.

Precedence, highest first (most GATE traps are here):

Level Operators Associativity
Postfix a[i] f() . -> x++ x-- left to right
Unary ++x --x *p &x ! ~ - sizeof (type) right to left
Multiplicative, additive * / %, then + - left to right
Shift, relational, equality << >>, then < <= > >=, then == != left to right
Bitwise &, then ^, then | left to right
Logical &&, then || left to right
Conditional, assignment ?:, then = += ... right to left
Comma , left to right

So *p++ is *(p++): use the value at p, then advance p. ++*p increments the value pointed to.

Short-circuit: in a && b, b is not evaluated if a is 0; in a || b, not if a is nonzero. Side effects inside b then do not happen.

Post vs pre increment: x++ yields the old value, ++x the new one.

Usual arithmetic conversions: in int vs unsigned int comparisons the int is converted to unsigned, so -1 > 1u is true.

Modifying a variable twice in one expression without a sequence point (i = i++ + ++i) is undefined behaviour; there is no single correct output.

2. Control flow and macros

switch falls through. Execution jumps to the matching case and runs every statement below it until a break or the end of the switch. default runs only when no case matches (or when control falls into it).

Loops. Trace the loop variable and the condition carefully:

  • In while (n-- > 0) the test uses the old n, then decrements. The body sees the decremented value, and after the loop ends n is one less than the value that failed the test.
  • for (init; cond; update): update runs after each pass, before the next test.
  • break leaves the innermost loop or switch; continue jumps to the next iteration (in a for, to the update).

To count iterations of nested loops, count how many times the inner body runs for each outer value and add.

Macros are text substitution done by the preprocessor before compilation. No values are computed and no parentheses are added:

  • #define SQ(x) x * x makes SQ(2 + 3) into 2 + 3 * 2 + 3, which is 11.
  • The safe form is #define SQ(x) ((x) * (x)). Even then, SQ(i++) increments i twice.

Truth values. Any nonzero value is true, zero is false. Relational and logical operators produce int 1 or 0. So if (x = 0) assigns 0 and is always false, a classic trap.

Conditional operator: c ? a : b evaluates only one of a and b.

3. Pointers, arrays and strings

A pointer holds an address. &x gives the address of x; *p reads or writes the object at p.

Arrays and pointers. In most expressions an array name decays to a pointer to its first element, so a[i]≡*(a + i). Pointer arithmetic is scaled: if p is an int *, p + 1 points to the next int, which is sizeof(int) bytes further. The difference p - q of two pointers into one array counts elements, not bytes.

Two-dimensional arrays are stored row by row. For int m[R][C], m[i][j] ≡ *(*(m + i) + j): m + i is a pointer to row i, *(m + i) is that row (decaying to a pointer to its first element), then + j moves along the row.

Strings are char arrays ending in '\0'.

  • char s[] = "GATE"; is an array of 5 chars: sizeof(s) is 5, strlen(s) is 4. Its contents may be changed.
  • char *t = "GATE"; is a pointer to a string literal: sizeof(t) is the pointer size, and writing to *t is undefined behaviour.
  • printf("%s", p) prints from p up to the '\0'.

An array parameter is really a pointer. In void f(int a[]), sizeof(a) is the pointer size, not the array size. Pass the length separately.

Pointer to pointer: with int **q = &p, *q is p and **q is the int itself.

An uninitialised local pointer holds garbage; dereferencing it, or a pointer to freed memory (dangling pointer), is undefined behaviour.

10a[0]100020a[1]100430a[2]100840a[3]101250a[4]1016ap = a + 3addresses with 4-byte int: p + 1 adds 4 bytes, p - a = 3 elements
An int array and a pointer into it: indexing and pointer arithmetic count elements

4. Functions, scope and storage classes

C passes every argument by value. The function gets a copy, so assigning to a parameter does not change the caller's variable. To let a function change a caller's variable, pass its address and assign through the pointer (*x = ...). Arrays look as if passed by reference only because what is copied is a pointer to the first element.

Scope (where a name is visible) and lifetime (how long the object exists) are different things.

Storage class Where declared Scope Lifetime Default value
auto (default local) inside a block the block until the block exits garbage
register inside a block the block until the block exits garbage; cannot take its address
static local inside a block the block whole program; initialised once 0
global outside functions file, from declaration on; other files via extern whole program 0
static global outside functions this file only (internal linkage) whole program 0
extern anywhere declares a global defined elsewhere — —

A static local keeps its value between calls; its initialiser runs only once.

Shadowing: an inner declaration hides an outer one with the same name inside its block. GATE questions mix a global x, a parameter x and a block-local x; find which x each line refers to.

Static vs dynamic scoping. C uses static (lexical) scoping: a free variable in a function refers to the declaration visible where the function is written, not to the caller's variable. Under dynamic scoping it would use the most recent binding in the call chain.

Dynamic memory: malloc returns memory that lives until free. Returning the address of a local variable gives a dangling pointer.

Formulas to remember

Array indexing
a[i]≡*(a + i)
Address of an element
&a[i]=base+i×sizeof(element)
2-D array element (row major)C = number of columns
&m[i][j]=base+(i⋅C+j)×sizeof(element)
Division identityInteger division truncates towards zero
(a/b)⋅b+a % b=a

Common mistakes

  • Reading *p++ as (*p)++; postfix ++ binds tighter, so the pointer moves.
  • Forgetting that && and || skip the right side, so its side effects do not happen.
  • Missing switch fall-through when a case has no break.
  • Evaluating a macro like a function; it is text substitution, so precedence can change the result.
  • Counting pointer differences in bytes; p - q counts elements.
  • Treating sizeof of an array parameter or a char * as the array length.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Pointer arithmetic on an array

numerical

What does this print?

int a[] = {10, 20, 30, 40, 50};
int *p = a + 1;
p += 2;
printf("%d ", *p);
printf("%d ", *(p - 2));
printf("%d ", p[1]);
printf("%d\n", (int)(p - a));
  1. Step 1: Where does p point after the two statements?

    Try it on paper first.

Example 2: A static local across calls

numerical

What does this print?

int f(void) {
    static int c = 0;
    c += 2;
    return c;
}
int main(void) {
    int s = 0;
    for (int i = 0; i < 3; i++)
        s += f();
    printf("%d\n", s);
    return 0;
}
  1. Step 1: When is c initialised?

    Try it on paper first.

Example 3: Call by value vs passing addresses

numerical

What does this print?

void swap1(int x, int y)   { int t = x;  x = y;   y = t; }
void swap2(int *x, int *y) { int t = *x; *x = *y; *y = t; }
int main(void) {
    int a = 1, b = 2;
    swap1(a, b);
    printf("%d %d ", a, b);
    swap2(&a, &b);
    printf("%d %d\n", a, b);
    return 0;
}
  1. Step 1: What does swap1 change?

    Try it on paper first.

Example 4: Integer division and remainder with negatives

numerical

What does this print (C99 or later)?

int x = 7, y = 2;
printf("%d %d %d %d\n", x / y, x % y, -x / y, -x % y);
  1. Step 1: Positive operands first.

    Try it on paper first.

Previous year questions

51 official GATE CSE questions on this topic, newest first.

Practise these 51 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE CSE syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.