Basic Study Questions
Multiple Choice · Week 1: Computers, Programs, and the C Toolchain
Question 1: Which Tool Reports This Error
A build ends with undefined reference to `printff`. The message has no line and column, and no caret under the source. Which stage of the toolchain produced it?
C: "undefined reference" is the linker's vocabulary. The call was accepted when the file was compiled; only when the linker searched all object files and libraries did it find that no body for the function exists. Compiler errors, by contrast, carry a file, line and column.
Multiple Choice · Week 2: History, Standards, and the Compilation Model
Question 2: What gcc -c Produces
You run gcc -c era.c -o era.o. What does era.o contain?
C: -c stops after the assembler. The result is an object file with real machine instructions, and the functions it calls but does not define show up as undefined symbols (U in nm). The linker resolves them in the last phase. -E gives the first option and -S the second.
Multiple Choice · Week 3: Program Structure, Style, and Basic Output
Question 3: Reporting Failure From Main
A program cannot open its input file and prints a message to stderr. What should main do so that a shell script running ./prog && next_step behaves correctly?
B: the value returned from main is the exit status, and &&, || and $? branch on it; zero means success, anything else means failure. A program that always returns 0 breaks every script around it. void main() is not standard C.
Multiple Choice · Week 4: Data Representation
Question 4: Signed Overflow Of INT_MAX
On a machine with 32-bit two's complement int, what does the C standard say about evaluating INT_MAX + 1 at run time?
D: signed overflow is undefined behavior, not wrap-around. Only unsigned arithmetic is defined to wrap. Because the compiler may assume signed overflow never occurs, it can delete a bounds check that relies on it, and the program may behave differently at -O0 and -O2.
Multiple Choice · Week 5: Variables, Types, and Constants
Question 5: The Countdown That Never Ends
What is wrong with this loop?
size_t n = 3; for (size_t i = n - 1; i >= 0; i--) { printf("%zu ", i); }
D: size_t is unsigned, so every value is at least 0. When i is 0, i-- wraps to the largest size_t and the loop keeps going. Loop upward, use a signed type, or restructure the condition, for example for (size_t i = n; i-- > 0; ).
Multiple Choice · Week 6: Operators and Expressions
Question 6: Mask Test With Wrong Precedence
What does this fragment print, and why?
int flags = 0x08; int mask = 0x04; if (flags & mask == 0) { puts("clear"); } else { puts("set"); }
B: the bitwise operators bind more loosely than ==. So mask == 0 is evaluated first and gives 0, then flags & 0 is 0, which is false, and the else branch prints "set". The intended test needs parentheses: (flags & mask) == 0. The code is legal; only -Wparentheses warns.
Output Question · Week 6: Operators and Expressions
Question 7: Division, Increment, Short-Circuit
What does this program print?
#include <stdio.h> static int trace(char c, int value) { putchar(c); return value; } int main(void) { printf("%d %d %d %d\n", 7 / 2, -7 / 2, 7 % 2, -7 % 2); printf("%d %d\n", 2 + 3 * 4, 10 - 4 - 3); printf("%g\n", 7 / 2 * 2.0); int i = 5; int a = i++; int b = ++i; printf("%d %d %d\n", a, b, i); if (trace('A', 0) && trace('B', 1)) { putchar('X'); } if (trace('C', 1) || trace('D', 1)) { putchar('Y'); } putchar('\n'); return 0; }
Show answer
3 -3 1 -1 14 3 6 5 7 7 ACY
Integer division truncates toward zero and the remainder takes the sign of the dividend, so -7 / 2 is -3 and -7 % 2 is -1. 7 / 2 * 2.0 is (7 / 2) * 2.0 = 3 * 2.0 = 6. Post-increment yields the old value (a = 5), pre-increment the new one (b = 7). The first if prints A and skips B because && short-circuits on 0; the second prints C and skips D because || stops at 1, then Y.
Multiple Choice · Week 7: Type Conversions
Question 8: Where To Place The Cast
With int total = 7, count = 2;, which expression evaluates to 3.5?
B: the cast applies to total first, so the division is double divided by int and is done in floating point. In the other three, total / count is an integer division that already truncated 3.5 to 3, so widening afterwards only gives 3.0.
Output Question · Week 7: Type Conversions
Question 9: Conversions That Surprise
What does this program print? (The compiler may warn about the signed/unsigned comparison; the output is still fully defined.)
#include <stdio.h> int main(void) { int a = -1; unsigned b = 1; printf("%d\n", a < b); printf("%d\n", a < (int)b); char x = 100, y = 100; int sum = x + y; printf("%d\n", sum); printf("%d %d\n", (int)3.99, (int)-3.99); int total = 7, count = 2; printf("%.1f %.1f\n", (double)total / count, (double)(total / count)); size_t n = 0; printf("%d\n", n - 1 > 5); return 0; }
Show answer
0 1 200 3 -3 3.5 3.0 1
In a < b the int -1 is converted to unsigned and becomes a huge value, so the result is 0; casting b to int makes the comparison signed and gives 1. The two char values are promoted to int, so the sum is 200. Casting a double to int truncates toward zero. (double)total / count is 3.5, but (double)(total / count) widens an already truncated 3. Finally n - 1 wraps to the largest size_t, which is greater than 5.
Multiple Choice · Week 8: Formatted Input and Output
Question 10: Retrying scanf On Bad Input
The user types abc and presses Enter. What does this loop do?
int n; while (scanf("%d", &n) != 1) { puts("again"); }
B: %d stops at the first character that cannot be part of a number and leaves it unread. scanf returns 0, the loop retries, meets the same abc, and fails again at full speed. The fix is to discard the rest of the line (for example with a getchar loop) before retrying.
Output Question · Week 8: Formatted Input and Output
Question 11: printf Width And Precision
What does this program print?
#include <stdio.h> int main(void) { printf("[%5d][%-5d][%05d][%+d]\n", 42, 42, 42, 42); printf("[%8.3f][%.2f][%.3s][%*d]\n", 3.14159, 3.14159, "abcdef", 6, 42); printf("%x %X %o %c %%\n", 255, 255, 8, 65); return 0; }
Show answer
[ 42][42 ][00042][+42] [ 3.142][3.14][abc][ 42] ff FF 10 A %
Width pads to a minimum field size, - left-aligns, 0 pads with zeros and + forces a sign. Precision on %f is the number of digits after the point (the value is rounded), on %s it is a maximum number of characters. %*d takes the width from the argument list (6). 255 is ff in hex, 8 is 10 in octal, 65 is 'A', and %% prints one percent sign.
Multiple Choice · Week 9: Conditional Statements
Question 12: Which If Owns The Else
What does this program fragment print?
int a = 1, b = 0; if (a > 0) if (b > 0) puts("both"); else puts("else");
C: an else attaches to the nearest unmatched if, whatever the indentation suggests. Here that is if (b > 0), which is false, so "else" is printed. Braces around the inner if remove the ambiguity.
Output Question · Week 9: Conditional Statements
Question 13: Switch Without A Break
What does this program print?
#include <stdio.h> static void classify(char grade) { switch (grade) { case 'A': puts("excellent"); case 'B': puts("good"); break; case 'C': case 'D': puts("pass"); break; default: puts("other"); } } int main(void) { classify('A'); classify('D'); classify('B'); classify('x'); return 0; }
Show answer
excellent good pass good other
A case label is only a jump target. classify('A') enters at case 'A', prints "excellent", has no break, and falls through into case 'B', printing "good" before the break. 'D' shares its action with 'C' through grouped labels, 'B' prints only "good", and anything else reaches default.
Output Question · Week 10: Loops and Flow Control
Question 14: Nested Loops With Break And Continue
What does this program print?
#include <stdio.h> int main(void) { for (int i = 0; i < 4; i++) { if (i == 1) { continue; } for (int j = 0; j < 3; j++) { if (j == i) { break; } printf("%d%d ", i, j); } } putchar('\n'); int k = 0; while (k < 6) { k++; if (k % 2 == 0) { continue; } printf("%d ", k); } putchar('\n'); size_t n = 0; int runs = 0; for (size_t i = 0; i + 1 < n; i++) { runs++; } printf("runs = %d\n", runs); int m = 0; do { m += 3; } while (m < 0); printf("m = %d\n", m); return 0; }
Show answer
20 21 30 31 32 1 3 5 runs = 0 m = 3
In the nested loop, i == 0 breaks out of the inner loop immediately (j is 0), i == 1 is skipped by continue, and i == 2 and i == 3 print j from 0 up to just before j == i. In the while loop the increment comes before continue, so only odd values are printed. With n == 0 the test i + 1 < n is false at once, so the half-open style handles the empty case; i < n - 1 would wrap. The do-while body runs once even though its condition is false from the start.
Classic Question · Week 10: Loops and Flow Control
Question 15: Loop Invariants And Off-By-One
State what a loop invariant is. Use one to explain why a "find the maximum" loop starts with maximum = values[0] and i = 1, and why that code is wrong for an empty array. Then explain why the half-open range [0, n) is the preferred way to write a counting loop.
Show answer
An invariant is a statement that is true before the loop starts, true after every iteration, and therefore true when it ends. For the maximum loop it is: maximum is the largest of values[0..i-1]. Initializing maximum with values[0] makes it true for the one-element range before the first iteration, which is why the loop starts at index 1; the body keeps it true, and when the loop ends with i == n the invariant says maximum is the largest of the whole array. The invariant also exposes the edge case: it assumes values[0] exists, so for n == 0 the code reads a nonexistent element and needs a guard before the loop.
In for (size_t i = 0; i < n; i++) the iteration count is visible as n, an empty range needs no special case (the test is false at once), and adjacent ranges [0, k) and [k, n) join with no gap or overlap. The closed form i <= n - 1 needs arithmetic, and for n == 0 on an unsigned type n - 1 wraps to a huge value. When a loop is wrong by one, check the first element, the last element, and the zero-element case.
Classic Question · Week 11: Functions
Question 16: Pass By Value And The Swap
A student writes void swap(int a, int b) that exchanges its two parameters through a temporary, and calls swap(x, y). It compiles without warnings, yet x and y are unchanged. Explain why, what the function must receive instead, and how a function that can fail should report it.
Show answer
C passes every argument by value: the parameters a and b are separate variables initialized with copies of x and y. The function swaps the copies and then its stack frame is discarded, so the caller's variables are never touched. This is a guarantee, not a defect: a function cannot silently alter variables it was handed.
To modify the caller's variables the function must receive their addresses: void swap(int *a, int *b), called as swap(&x, &y), using *a and *b in the body. The addresses are still copied, but both copies refer to the same objects. This is also why scanf needs &.
C has no exceptions, so a function that can fail reports it through its result: return a value outside the valid range (for example n for "not found"), or return a status such as bool and write the real result through a pointer, or return NULL for pointer results. The caller must check it.
Classic Question · Week 12: One- and Multi-Dimensional Arrays
Question 17: Out Of Range Array Access
What does C do when a program writes to values[10] on an array of five elements? Why is it worse when the program does not crash, and how can you find such a bug?
Show answer
Nothing checks the index. values[i] is defined as the object at address values + i * sizeof(element), so the program simply reads or writes whatever lives at that address, and the behavior is undefined. Depending on layout it may hit padding (no visible effect), another local variable (that variable changes for no apparent reason), the saved return address (a crash far from the bug), or an unmapped page (an immediate segmentation fault).
The silent cases are the dangerous ones. A bug that always crashes gets fixed the same day; one that quietly corrupts a neighboring variable may hide for years and then surface somewhere innocent. It is also the defect class behind many security vulnerabilities.
Use tools: compile with -Wall -Wextra -g -fsanitize=address, and AddressSanitizer reports the exact line, the array and the offset of the access. In the code itself, keep the length next to the array, use size_t indices in the half-open range [0, n), and check an index before using it when it comes from outside.
Classic Question · Week 13: Introduction to Pointers
Question 18: Array Decay And sizeof
Inside a function with the parameter int values[], sizeof values reports 8 (not 20), yet the function can still modify the caller's array. Explain both facts with array decay, and say why the length must be passed separately.
Show answer
In most expressions an array name decays into a pointer to its first element, and values[i] is defined as *(values + i). Decay does not happen as the operand of sizeof or &, so where the array is declared sizeof values is the full size (20 for five ints). C has no array parameters: a parameter written int values[] is rewritten by the compiler to int *values, so inside the function sizeof values is the size of a pointer, typically 8.
The function can modify the caller's data because what was copied is the pointer: it still points at the caller's memory, so writing through it changes the original. Pass-by-value was never broken; the pointer itself was copied faithfully.
Since the function receives only an address, no length travels with it, so the length has to be passed as a separate parameter, typically a size_t n.
Multiple Choice · Week 14: Strings and Character Handling
Question 19: Bounded Copy With strncpy
What is the problem with this code?
char dst[5]; strncpy(dst, "hello world", 5); printf("%s\n", dst);
A: when the source is at least n bytes long, strncpy copies exactly n characters and writes no terminator. The next %s or strlen runs off the end of the array. snprintf(dst, sizeof dst, "%s", src) always terminates.
Output Question · Week 14: Strings and Character Handling
Question 20: Length, Overlap, And strtok
What does this program print?
#include <stdio.h> #include <string.h> int main(void) { char buf[16] = "hello"; printf("%zu %zu\n", strlen(buf), sizeof buf); char s[] = "abcdef"; memmove(s + 2, s, 3); printf("%s\n", s); printf("%d\n", strcmp("abc", "abc") == 0); char t[] = "a,b"; char *p = strtok(t, ","); printf("%s %s\n", p, t); const char *lit = "hello"; char arr[] = "hello"; arr[0] = 'J'; printf("%s %s %zu %zu\n", lit, arr, strlen(arr), sizeof arr); return 0; }
Show answer
5 16 ababcf 1 a a hello Jello 5 6
strlen counts characters before the terminator (5) while sizeof is the whole array (16); for char arr[] = "hello" they are 5 and 6. memmove copies "abc" into positions 2 to 4 as if through a temporary, giving "ababcf"; memcpy on overlapping regions would be undefined. strcmp returns 0 for equal strings, so the comparison is 1. strtok writes a terminator over the first comma, so t itself now reads as just "a". Modifying arr is fine because it is a copy; the literal behind lit is left alone.