These are the notes for C Coding Questions, episode 30, the last episode of the series: the output round of a placement test, where you read a short program and say what it prints. Six classic traps in three questions: printf's return value, sizeof on an array vs a pointer, static local variables, switch fall-through, signed vs unsigned comparison, and i++ + ++i (undefined behaviour).
Each one follows the same steps: read the code, make the obvious guess, run it for real, see the real output or warning, understand why, and write it the right way.
Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc, Linux x86-64, where int is 4 bytes and a pointer is 8), the SyntaxPilot compiler's C command with warnings on, and every output below is real. The "5 5" comparison in Q3b was compiled with clang 18.1.3.
Real-life pictures
| In real life | In C |
|---|---|
| a bill printer that tells you how many letters it printed | printf returns a count: the characters it wrote |
| handing over the key to a cupboard, not the cupboard | an array parameter is a pointer: sizeof gives 8, not 20 |
| a temple's visitor counter vs a slate wiped for every visitor | a static local keeps its value; a normal local starts again |
| a lift that keeps going down until you press stop | switch fall-through until break |
| a car's odometer rolling back past zero shows 999999 | unsigned wrap-around: -1 becomes 4294967295 |
| two people writing on one board at the same moment | i++ + ++i: two changes, no order, undefined behaviour |
Q1a: What does printf return?
Question. What do these print?
#include <stdio.h>
int main() {
int n = printf("SyntaxPilot\n");
printf("n = %d\n", n);
printf("%d\n", printf("Hi "));
printf("%d\n", printf("%d", 100));
return 0;
}
Obvious guesses. n = 0 ("it worked"), n = 11 (the letters), or "printf returns nothing".
Real output:
SyntaxPilot
n = 12
Hi 3
1003
Why. printf returns an int: the number of characters it wrote (or a negative number if writing failed). "SyntaxPilot\n" is 11 letters + 1 newline = 12. In printf("%d\n", printf("Hi ")), C must compute the argument before calling the outer printf, so the inner one runs first: it prints Hi and returns 3, then the outer prints 3. Same for printf("%d", 100): it prints 100 and returns 3, so the line reads 1003.
Q1b: sizeof on an array parameter
Question. Five marks, average 80. What does average compute?
#include <stdio.h>
double average(int a[]) {
int n = sizeof(a) / sizeof(a[0]); /* how many marks? */
int total = 0;
for (int i = 0; i < n; i++) total += a[i];
printf("average() thinks n = %d\n", n);
return (double)total / n;
}
int main() {
int marks[] = {70, 80, 90, 60, 100};
printf("main() says n = %zu\n", sizeof(marks) / sizeof(marks[0]));
printf("average = %.2f\n", average(marks));
return 0;
}
Obvious guess. sizeof(a) is 5 × 4 = 20 bytes, so n = 20 / 4 = 5 and the average is 80.00.
Real compiler output:
main.c: In function 'average':
main.c:4:19: warning: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument]
4 | int n = sizeof(a) / sizeof(a[0]); /* how many marks? */
| ^
main.c:3:20: note: declared here
3 | double average(int a[]) {
| ~~~~^~~
Real output:
main() says n = 5
average() thinks n = 2
average = 75.00
Why. A parameter written int a[] is exactly int *a. When an array is passed to a function it decays to a pointer to its first element; the size is not passed. sizeof(a) is the size of a pointer, 8 bytes on a 64-bit system, and 8 / 4 = 2. The average used only 70 and 80.
The right way: count where it's a real array, and pass n.
#include <stdio.h>
double average(const int a[], int n) { /* the caller passes n */
int total = 0;
for (int i = 0; i < n; i++) total += a[i];
return (double)total / n;
}
int main() {
int marks[] = {70, 80, 90, 60, 100};
int n = sizeof(marks) / sizeof(marks[0]); /* works HERE: a real array */
int *p = marks;
printf("sizeof(marks) = %zu, sizeof(p) = %zu\n", sizeof(marks), sizeof(p));
printf("n = %d, average = %.2f\n", n, average(marks, n));
return 0;
}
Real output (no warning):
sizeof(marks) = 20, sizeof(p) = 8
n = 5, average = 80.00
Q2a: Counting calls (static)
Question. What does this print?
#include <stdio.h>
void visit(void) {
int count = 0; /* how many visits so far? */
count++;
printf("visit number %d\n", count);
}
int main() {
visit();
visit();
visit();
return 0;
}
Obvious guess. visit number 1, 2, 3.
Real output:
visit number 1
visit number 1
visit number 1
Why. A normal local variable (an automatic variable) is created each time the function starts and destroyed when it returns. Every call gets a fresh count set to 0.
The right way: static. A static local variable is created once, before main starts, and keeps its value between calls. Its initialiser runs only that once, it starts at 0 if you give no value, and it is still visible only inside its function.
#include <stdio.h>
void visit(void) {
int normal = 0; /* made again on every call */
static int count = 0; /* made once, keeps its value */
normal++;
count++;
printf("visit number %d (normal = %d)\n", count, normal);
}
int main() {
visit();
visit();
visit();
return 0;
}
Real output:
visit number 1 (normal = 1)
visit number 2 (normal = 1)
visit number 3 (normal = 1)
Q2b: switch without break
Question. What do remark('B') and remark('A') print?
#include <stdio.h>
void remark(char grade) {
printf("%c: ", grade);
switch (grade) {
case 'A': printf("Excellent ");
case 'B': printf("Good ");
case 'C': printf("Average ");
default: printf("Fail ");
}
printf("\n");
}
int main() {
remark('B');
remark('A');
return 0;
}
Obvious guess. B: Good and A: Excellent.
Real output:
B: Good Average Fail
A: Excellent Good Average Fail
Why. A case is a label, a place to jump to, not a wall. switch jumps to the matching label and then runs every statement below it until a break (or the end of the switch). That's fall-through. gcc's -Wall doesn't warn about it in C; -Wextra enables -Wimplicit-fallthrough, which does.
The right way: break after every case, and a comment when two cases share code on purpose.
#include <stdio.h>
void remark(char grade) {
printf("%c: ", grade);
switch (grade) {
case 'A': printf("Excellent"); break;
case 'B': printf("Good"); break;
case 'C': printf("Average"); break;
case 'D': /* D and E share one remark: */
case 'E': printf("Pass"); break; /* fall-through on purpose */
default: printf("Fail"); break;
}
printf("\n");
}
int main() {
remark('B');
remark('A');
remark('C');
remark('D');
remark('F');
return 0;
}
Real output:
B: Good
A: Excellent
C: Average
D: Pass
F: Fail
Q3a: Is -1 less than 1?
Question. What does this print?
#include <stdio.h>
int main() {
int x = -1;
unsigned int u = 1;
if (x < u) printf("-1 < 1\n");
else printf("-1 > 1 ?!\n");
printf("-1 as unsigned = %u\n", (unsigned int)x);
return 0;
}
Obvious guess. -1 < 1.
Real output:
-1 > 1 ?!
-1 as unsigned = 4294967295
Why. An unsigned int holds only 0 and positive numbers: 0 to 4294967295 (2³² − 1) with 32 bits. When an int and an unsigned int meet in a comparison or an arithmetic operation, the usual arithmetic conversions convert the int to unsigned int. -1 becomes 2³² − 1 = 4294967295 (every bit set), and 4294967295 < 1 is false.
This bites in real code because sizeof and strlen give size_t, an unsigned type: if (-1 < sizeof(int)) is false. gcc's -Wall does not warn in C (it does in C++). -Wextra turns on -Wsign-compare, which gives, for this program:
main.c:6:11: warning: comparison of integer expressions of different signedness: 'int' and 'unsigned int' [-Wsign-compare]
The right way: check the sign first.
#include <stdio.h>
int less(int x, unsigned int u) { /* is x < u, done right */
if (x < 0) return 1; /* a negative is below every unsigned */
return (unsigned int)x < u; /* both are >= 0 now */
}
int main() {
printf("-1 < 1u: %s\n", less(-1, 1) ? "yes" : "no");
printf(" 5 < 1u: %s\n", less(5, 1) ? "yes" : "no");
printf(" 0 < 1u: %s\n", less(0, 1) ? "yes" : "no");
return 0;
}
Real output:
-1 < 1u: yes
5 < 1u: no
0 < 1u: yes
(Another fix: convert both to a wider signed type, (long long)x < (long long)u, which holds every int and every unsigned int.)
Q3b: i++ + ++i
Question. What do these print?
#include <stdio.h>
int main() {
int i = 5;
int r = i++ + ++i;
printf("r = %d\n", r);
int k = 5;
printf("%d %d\n", k, k++);
return 0;
}
Obvious guesses. 11, 12 or 13 for r; 5 5, 6 5 or 5 6 for the second line.
Real compiler output:
main.c: In function 'main':
main.c:5:19: warning: operation on 'i' may be undefined [-Wsequence-point]
5 | int r = i++ + ++i;
| ^~~
main.c:9:27: warning: operation on 'k' may be undefined [-Wsequence-point]
9 | printf("%d %d\n", k, k++);
| ~^~
Real output (gcc):
r = 12
6 5
clang 18 on the same code prints r = 12 and 5 5.
Why. i++ gives the old value and then adds one (post-increment); ++i adds one and then gives the new value (pre-increment). But here i is modified twice in one expression with no sequence point between the two changes (a sequence point is a moment where every earlier change must be finished, e.g. the end of a full statement, or &&, ||, , as an operator). In printf("%d %d\n", k, k++), k is read and modified in two arguments whose order isn't fixed. The C standard calls both undefined behaviour: there is no correct output, and different compilers (or flags) really do print different things.
The interview answer is not "12". It's: "This is undefined behaviour; any output is possible. I would rewrite it."
The right way: one change per statement.
#include <stdio.h>
int main() {
int i = 5;
int a = i++; /* a = 5, then i = 6 */
int b = ++i; /* i = 7, then b = 7 */
printf("a + b = %d\n", a + b);
int k = 5;
printf("%d ", k);
k++;
printf("%d\n", k);
return 0;
}
Real output (no warnings, the same on every compiler):
a + b = 12
5 6
The six rules
| # | Rule | Real result |
|---|---|---|
| 1 | printf returns the number of characters printed (\n counts) |
n = 12, 1003 |
| 2 | An array parameter is a pointer: pass the length | n = 2 → warning -Wsizeof-array-argument |
| 3 | A static local is made once and keeps its value | 1, 2, 3 vs 1, 1, 1 |
| 4 | switch falls through until break |
Good Average Fail |
| 5 | int vs unsigned: the int becomes unsigned |
-1 > 1, 4294967295 |
| 6 | Two changes to one variable in one expression: undefined behaviour | warning -Wsequence-point, gcc 6 5, clang 5 5 |
Complexity isn't the point today: each of these is a single step. The skill is reading code the way the compiler does.
Common mistakes (and the real results)
| Mistake | What happens | Why | Fix |
|---|---|---|---|
thinking printf("SyntaxPilot\n") returns 11 |
it returns 12 | the \n is a character |
count every character |
sizeof(a) inside void f(int a[]) |
warning: 'sizeof' on array function parameter ..., n = 2 |
a is an int * |
pass n |
int count = 0; to count calls |
1, 1, 1 |
a new local every call | static int count = 0; |
a case with no break |
Good Average Fail |
fall-through | break;, or a comment when on purpose |
if (-1 < sizeof(int)) |
false | -1 becomes unsigned | check the sign first, or -Wextra |
for (unsigned i = 5; i >= 0; i--) |
never ends: 5 4 3 2 1 0 4294967295 ... |
i >= 0 is always true |
use int i, or for (unsigned i = 6; i-- > 0; ) |
r = i++ + ++i; |
warning: operation on 'i' may be undefined |
undefined behaviour | one change per statement |
printf("%d %d", k, k++) |
gcc 6 5, clang 5 5 |
unspecified order + UB | print, then k++ |
Your turn: four numbers (answer)
Question.
char s[] = "hello";
char *p = "hello";
printf("%zu %zu %zu %zu\n", sizeof s, strlen(s), sizeof p, strlen(p));
Answer
Real output:
6 5 8 5
sizeof s= 6:sis a real array of 6 chars, the 5 letters plus the hidden'\0'that ends every string.strlen(s)= 5:strlencounts characters up to, not including, the'\0'.sizeof p= 8:pis a pointer (Q1b): 8 bytes on a 64-bit system, whatever it points to.strlen(p)= 5: the same string.
%zu is the printf format for size_t, the unsigned type sizeof and strlen give.
Full program (also checks the quiz):
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "hello";
char *p = "hello";
printf("%zu %zu %zu %zu\n", sizeof s, strlen(s), sizeof p, strlen(p));
int x = 10;
switch (x % 3) { case 0: printf("zero "); case 1: printf("one "); case 2: printf("two "); }
printf("\n");
return 0;
}
Real output:
6 5 8 5
one two
Practice questions (with solutions)
1. printf("%d", printf("%d", 12345))
Answer
123455: the inner printf prints 12345 and returns 5; the outer prints 5.
2. Can a static counter be shared by two functions?
Answer
Not a static local: it is visible only inside its own function. To share a counter between functions in one file, declare it outside any function, static int count = 0; at file scope (the static there means "visible only in this file"), or pass a pointer to it.
3. for (unsigned i = 5; i >= 0; i--)
#include <stdio.h>
int main() {
printf("%d\n", printf("%d", 12345));
int n = 0;
for (unsigned i = 5; i >= 0; i--) { /* i >= 0 is ALWAYS true */
printf("%u ", i);
if (++n == 8) break; /* stop the demo after 8 */
}
printf("\n");
return 0;
}
Real output (the loop is stopped after 8 rounds by the break, otherwise it never ends):
123455
5 4 3 2 1 0 4294967295 4294967294
Why
An unsigned is never below 0, so i >= 0 is always true; after 0, i-- wraps round to 4294967295. -Wextra warns: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]. Use int i, or count down with for (unsigned i = 6; i-- > 0; ).
Quick quiz
int x = 10;
switch (x % 3) {
case 0: printf("zero ");
case 1: printf("one ");
case 2: printf("two ");
}
What does it print? (A) one (B) one two (C) zero one two (D) nothing
Answer
(B) one two (real output: one two). 10 % 3 is 1, so the switch jumps to case 1, prints one, and falls through to case 2.
Interview questions
- What does
printfreturn? The number of characters written, or a negative value on error. - Why does
sizeofgive a different answer inside a function? The array parameter has decayed to a pointer. - How do you get the length of an array passed to a function? You can't from the pointer: pass it as a parameter (or use a sentinel such as
'\0'for strings). - What is a static local variable? Where does it live? Created once, keeps its value between calls; it lives in static storage (with globals), not on the stack.
- When is switch fall-through useful? When several cases share code, e.g.
case 'D': case 'E':. Comment it. - Why is
-1 < 1ufalse? The usual arithmetic conversions turn -1 intoUINT_MAX. - What is undefined behaviour? Code the C standard gives no meaning to: any result, including a crash or a "correct-looking" answer, is allowed.
- What is a sequence point? A point where all earlier side effects are complete: the end of a full expression,
&&,||,?:, the comma operator, a function call after its arguments. - Is
i = i++;defined? No:iis modified twice without a sequence point. Undefined behaviour. - Which gcc flags catch these?
-Wall(-Wsizeof-array-argument,-Wsequence-point),-Wextra(-Wsign-compare,-Wimplicit-fallthrough,-Wtype-limits).
Glossary
| Term | Meaning | Example |
|---|---|---|
| Output question | Read code, say exactly what it prints | the whole episode |
Return value of printf |
The number of characters written | 12 for "SyntaxPilot\n" |
sizeof |
The size of a type or object in bytes | sizeof(int) is 4 |
| Array decay | An array used as a value becomes a pointer to its first element | passing marks to average |
| Array parameter | int a[] in a parameter list, which is really int *a |
average(int a[]) |
-Wsizeof-array-argument |
gcc warning for sizeof on an array parameter |
Q1b |
| Local (automatic) variable | Made when the function starts, gone when it returns | int normal |
| Static local variable | Made once, keeps its value between calls | static int count |
| Storage duration | How long a variable exists | automatic vs static |
switch / case / default |
Jump to the matching label | the grade remarks |
break |
Leaves the switch (or a loop) | after every case |
| Fall-through | Running on into the next case's code | Good Average Fail |
| Signed / unsigned | Can / cannot hold negative numbers | int / unsigned int |
unsigned int |
0 to 4294967295 with 32 bits | 1u |
| Wrap-around | Going past the limit starts again from the other end | -1 → 4294967295 |
| Usual arithmetic conversions | The rules that bring both operands to one type | int → unsigned |
size_t |
The unsigned type of sizeof and strlen |
%zu |
-Wsign-compare |
Warns about signed/unsigned comparisons (-Wextra in C) |
Q3a |
Post-increment i++ |
Gives the old value, then adds one | a = i++ |
Pre-increment ++i |
Adds one, then gives the new value | b = ++i |
| Sequence point | A moment when every earlier change is finished | the end of a statement |
| Undefined behaviour (UB) | Code the C standard gives no meaning to | i++ + ++i |
| Unspecified order of evaluation | The standard doesn't say which argument is computed first | printf(..., k, k++) |
-Wsequence-point |
gcc warning for changes without a sequence point | Q3b |
'\0' (null character) |
The hidden byte that ends every C string | sizeof "hello" is 6 |
strlen |
Characters before the '\0' |
strlen("hello") is 5 |
Summary
- printf returns the characters it printed; an inner
printfruns before the outer one. - An array parameter is a pointer:
sizeofgives 8; count in the caller and passn. - A static local is made once and keeps its value; a normal local starts again every call.
- switch falls through until
break. - int vs unsigned: the int becomes unsigned, so
-1 > 1u; check the sign first. i++ + ++iandprintf("%d %d", k, k++)are undefined behaviour: say so, and write one change per statement.- Compile with
-Wall(and-Wextra): two of the six traps came with a warning under-Wall, and the others with-Wextra.
That's the end of C Coding Questions: thirty episodes and about ninety questions, from patterns to pointers, linked lists, stacks, files and output questions. Keep practising with the C++ Coding Questions series.