C expressions, control and objects
C tracing starts with types and sequencing. Do not assume that a familiar machine output proves a language guarantee. Keep automatic locals, static objects and pointed-to objects separate in a trace.
5.1 Types, conversions and integer arithmetic
Past papers · CS 2014–2026 (23 papers): 1 question, 1 mark
char, signed and unsigned integer types, floating types, pointers, arrays, structures and unions have different rules. sizeof(char) is always 1; other sizes are implementation-dependent. sizeof returns unsigned size_t. Integer promotions convert small integer types to int if all their values fit, otherwise to unsigned int. Ordinary character constants such as '7' have type int in C.
For mixed arithmetic, apply promotions and then the usual arithmetic conversions. Floating arithmetic uses the appropriate common floating type. For integers of the same signedness, use the higher rank. With mixed signedness: if unsigned rank is at least signed rank, convert to unsigned; otherwise use the signed type if it represents every value of the unsigned type; otherwise use the unsigned counterpart of the signed type. This explains why comparing a negative int with unsigned int can produce a surprising result.
Assignment converts the final value to the destination type. Integer division happens before assignment to a floating destination unless an operand is already floating: double z = 7/2; stores 3.0. Converting a representable finite floating value to integer truncates toward zero. Division by zero, and division of the most negative two's-complement value by , are undefined when the quotient does not fit.
5.2 Precedence, truth and sequencing
Past papers · CS 2014–2026 (23 papers): 1 question, 2 marks
| Binding order, strongest first | Operators | Associativity |
|---|---|---|
| Postfix | [] () . -> x++ x-- | Left |
| Unary and cast | ++x --x + - ! ~ * & sizeof (type) | Right |
| Multiplicative | * / % | Left |
| Additive | + - | Left |
| Shift | << >> | Left |
| Relational | < <= > >= | Left |
| Equality | == != | Left |
| Bitwise | &, then ^, then | | Left |
| Logical | &&, then || | Left |
| Conditional | ?: | Right |
| Assignment | = += -= *= /= %= <<= >>= &= ^= |= | Right |
| Comma operator | , | Left |
Precedence groups an expression; it does not schedule operand evaluation. Zero is false; nonzero is true. Relational and logical results have integer value 0 or 1. && evaluates its right operand only if the left is true; || only if the left is false. The condition of ?: is evaluated first, then just one branch. The comma operator sequences its operands; commas separating function arguments do not.
Prefix increment yields the new value; postfix increment yields the old value and also increments the object. A full expression ends at boundaries such as the semicolon of an expression statement. In a[i++], the index used is the old i. In *p++, the old pointed-to object is selected and the pointer advances; in (*p)++, the pointed-to value is incremented.
5.3 Bit operations and digit loops
Past papers · CS 2014–2026 (23 papers): 4 questions, 7 marks
Use unsigned operands for portable bit manipulations. Shift counts must be nonnegative and smaller than the width of the promoted left operand. Right shift of a negative signed value is implementation-defined in C11; invalid shift counts are undefined. Signed left shift needs its separate representability conditions; do not model it as general wraparound.
Set bit by OR with a suitably typed unsigned ; clear it by AND with the complemented mask; toggle it by XOR. Parenthesise bit tests: (u & mask) != 0. u & mask == 0 instead groups as u & (mask == 0).
For positive integers, repeated division by base extracts digits in reverse order via remainders. Accumulating value = b*value + digit appends a digit to the right. Preserve the original input if later steps need it.
5.4 Loops, branches and invariants
Past papers · CS 2014–2026 (23 papers): 10 questions, 18 marks
A for loop executes initialisation once, condition before each iteration, body, update, then condition again. continue in a for goes to the update; in a while it goes to the condition. do executes its body before testing. break exits the nearest loop or switch. An else attaches to the closest unmatched if. Separate if statements can both run after the first changes a value.
A switch jumps to a matching case or default, then continues through subsequent statements until break, return or the end. Cases are labels, not automatically separate branches. The controlling expression has integer type; case labels are distinct integer constant expressions.
Prove an invariant at initialisation and after one iteration, then combine it with the stopping condition. Termination needs a decreasing nonnegative measure or another argument; an invariant alone does not prove progress. A halving loop while (n>1) n/=2 with positive integer executes times. Applying the same loop to that count produces an iterated logarithm, with small inputs handled directly.
For positive integers , subtracting the smaller from the larger preserves : when , , and symmetrically when . Repeating until the values are equal returns the original greatest common divisor. Positivity matters: a zero operand can prevent progress in this subtraction-only trace.
5.5 Scope, storage duration and functions
Past papers · CS 2014–2026 (23 papers): 16 questions, 22 marks
C uses lexical scope: name lookup follows the program's block nesting, not the run-time caller chain. An inner declaration hides an outer declaration; after leaving the block, the outer name is visible again. Two local definitions of the same name in the same scope are not a way to overwrite a value.
| Declaration | Lifetime and initial state | Key distinction |
|---|---|---|
| Automatic local | Each block activation; indeterminate unless initialised | Each recursive call has a separate instance |
Local static | Entire program; initialised once, zero if omitted | Scope remains local; state persists across calls |
| File-scope object | Static duration; zero if omitted | Linkage may be external or internal |
File-scope static | Static duration, internal linkage | Name is confined to that translation unit |
extern declaration | Refers to an object defined elsewhere, normally | Declaration is not necessarily a definition |
register local | Automatic duration; allocation hint | C11 forbids applying & to it |
| Allocated object | Until deallocation | Accessed through pointers; not an automatic local |
Static-duration arithmetic objects default to zero; static-duration pointers default to null pointers. An uninitialised automatic value is not a usable random number. Typical machines use a run-time stack for automatic locals, data regions for static objects and a heap for allocation; C specifies durations, not physical segment names.
C passes all arguments by value, including pointers. Updating a formal pointer only changes that local copy. Writing through it can modify the caller's pointed-to object. To replace a caller's pointer, return the new pointer or pass its address as a pointer-to-pointer. A function cannot return a local automatic object's address for valid use after return. Use compatible prototypes; int f(void) explicitly takes no arguments in C11.
5.6 Records, allocation and declarations
Past papers · CS 2014–2026 (23 papers): 4 questions, 4 marks
Read declarations outward from the identifier, respecting parentheses. int *p[4] is an array of four pointers; int (*p)[4] points to a four-int array; int (*f)(int) is a pointer to a function taking and returning int. const int *p restricts modification through p; int *const p fixes the pointer itself. typedef introduces an alias, not a new object.
A structure stores all its members; p->field means (*p).field. Members appear in declaration order but may have padding between them and at the end. Size is not generally the sum of member sizes. A union overlays member storage and is large enough for its largest member, possibly with alignment padding. Do not infer an inactive member's value from ordinary arithmetic on the active one. Bit-field layout and widths need the implementation's specification.
#include <stdlib.h>
struct Node { int key; struct Node *next; };
struct Node *make_node(int key) {
struct Node *p = malloc(sizeof *p);
if (p != NULL) {
p->key = key;
p->next = NULL;
}
return p;
}
malloc returns uninitialised storage or null. calloc zeroes the allocated bytes; all-zero bytes need not represent every possible type's null or floating zero value. realloc can move a block and invalidate old pointers; on failure with nonzero requested size the old block remains valid. Assign its result to a temporary before replacing the only saved pointer. free(NULL) is permitted; double free and use after free are undefined. Losing the last pointer to an allocated block leaks that allocation.
5.7 Input, strings and preprocessing
Past papers · CS 2014–2026 (23 papers): 7 questions, 9 marks
A C string is a character sequence terminated by \0. char s[] = "lamp"; creates a writable array of five characters; char *p = "lamp"; points to a literal that must not be modified. Array assignment is not supported; pointer assignment does not copy characters. An array such as char s[4]="lamp"; contains no terminator and cannot safely be used as that string.
| Operation | Result or requirement |
|---|---|
strlen(s) | Number of characters before first null; excludes terminator; returns size_t |
sizeof s | Whole array's bytes if s is an array here; pointer bytes if s is a pointer |
strcpy(d,s) | Copies through null; destination must fit; no overlapping regions |
strcat(d,s) | Appends to existing terminated destination; room for both plus null |
strcmp(a,b) | Negative, zero or positive lexicographic comparison; not necessarily |
memmove(d,s,n) | Copies bytes and permits overlap; does not add a null automatically |
printf uses %d for int, %u for unsigned int, %zu for size_t, %c for a promoted character value, %s for a terminated string, and %p for a pointer passed as (void *)p. float promotes to double in variadic calls, so %f prints a double. scanf needs writable addresses: %d takes int *, %f takes float *, %lf takes double *. For a character array, scanf("%9s", a) needs at least ten slots and stops at whitespace; %c does not skip whitespace unless the format includes it. Check conversion counts. getchar() returns int so that character values and EOF can be distinguished.
Preprocessing replaces macro tokens before C evaluation. Parenthesise parameters and the whole expansion, but avoid side-effect arguments when a macro uses its parameter more than once. A function-like macro is not a function call. #include supplies declarations; conditional preprocessing uses #if, #ifdef and matching #endif.
Last-minute recall
- Operand types determine arithmetic before assignment converts the result.
- Unsigned wraparound does not justify signed overflow.
- Precedence is not evaluation order.
- Short-circuit operators may skip side effects.
- Static locals persist; automatic locals are per activation.
- Pointer parameters are copied, but the pointed-to object can be changed.
- String length excludes the terminator; storage includes it.
- Valid syntax does not guarantee defined execution.