МатематикаМоя статистика
Тест по языку C
100 вопросов в 11 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Типы и операторы, функции, указатели, массивы и строки, malloc и free, структуры, препроцессор, printf и stdio, неопределённое поведение и вычисления с плавающей точкой. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Types and operators9
What does this code print?
int a = 7, b = 2;
double r = a / b;
printf("%.1f\n", r);- 3.0
- 3.5
- 4.0
- It does not compile: an int expression cannot be assigned to a double
a / b has two int operands, so it is integer division: 7 / 2 is 3 (the fraction is discarded), and only then is 3 converted to 3.0 for the assignment. Expecting 3.5 is the classic mistake of thinking the double on the left makes the division floating-point — write (double)a / b or 7.0 / 2. Integer division never rounds up, so 4.0 is wrong too.
What does this code print (C99 or later)?
printf("%d %d\n", -7 / 2, -7 % 2);- -3 -1
- -4 1
- -3 1
- -4 -1
Since C99 integer division truncates toward zero, so -7 / 2 is -3, not -4 as floor division (e.g. Python's //) would give. The remainder is defined by (a / b) * b + a % b == a, so -7 % 2 = -7 - (-6) = -1: it takes the sign of the dividend. That is why a test like n % 2 == 1 misses negative odd numbers — use n % 2 != 0.
What is sizeof(char) in C?
- 8, because a char has 8 bits
- Always 1, by definition
- 2 on systems that use Unicode
- It depends on the compiler, just like sizeof(int)
sizeof measures sizes in units of char, so sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1 on every implementation. The number of bits in a char is CHAR_BIT from <limits.h> (at least 8, almost always exactly 8) — answering 8 confuses bytes with bits. Wide characters use wchar_t, not char.
What does this code print?
int i = -1;
unsigned int u = 1;
if (i < u)
puts("less");
else
puts("not less");- not less
- less
- Nothing: comparing signed and unsigned values is a compile error
- It is undefined behaviour, so the output is unpredictable
By the usual arithmetic conversions, an int compared with an unsigned int of the same rank is converted to unsigned. -1 becomes UINT_MAX (4294967295 with 32-bit int), which is not less than 1. The conversion is well defined (modulo 2^N), and compilers only warn (-Wsign-compare). It typically bites when an int index is compared with the size_t result of strlen() or sizeof — keep both operands signed or both unsigned.
Assume 16-bit unsigned short and 32-bit int. What happens when this function is called with x = 65535?
unsigned int sq(unsigned short x)
{
return x * x;
}- It returns 4294836225, because the result is returned as unsigned int
- Undefined behaviour: x is promoted to signed int and 65535 * 65535 overflows int
- It returns 1, because unsigned short arithmetic wraps modulo 65536
- It does not compile without an explicit cast to unsigned int
The integer promotions convert any type narrower than int to int when int can hold all its values — so unsigned short becomes signed int, not unsigned int. x * x is then int * int, and 4294836225 is far above INT_MAX (2147483647): signed overflow, undefined behaviour. The return type does not affect how the multiplication is done, and arithmetic is never performed in 16 bits. Fix: return (unsigned int)x * x;.
What does this code print?
int i = 5;
int j = i++;
int k = ++i;
printf("%d %d %d\n", i, j, k);- 7 6 7
- 6 5 6
- 7 5 7
- 7 5 6
Postfix i++ yields the old value (5) and then increments i to 6; prefix ++i increments first (to 7) and yields the new value. The two modifications are in separate statements, so everything is well defined: i = 7, j = 5, k = 7.
Which statement about the plain type char is true?
- Whether char is signed or unsigned is implementation-defined; char, signed char and unsigned char are three distinct types
- char is always signed, exactly like signed char
- char is always unsigned, because character codes are never negative
- char is signed on 64-bit systems and unsigned on 32-bit systems
The standard leaves the signedness of plain char to the implementation: compilers for x86 usually make it signed, for ARM Linux unsigned (gcc has -fsigned-char / -funsigned-char). Code that stores byte values above 127 in char, or keeps getchar()'s result (where EOF is -1) in a char, therefore behaves differently across platforms. Use unsigned char for raw bytes and int for getchar.
What does this code print?
unsigned char a = 200, b = 100;
int s = a + b;
unsigned char c = a + b;
printf("%d %d\n", s, c);- 44 44
- 300 44
- 300 300
- Nothing definite: 200 + 100 overflows unsigned char, which is undefined behaviour
The integer promotions convert both operands to int before the addition, so a + b is the int 300 and no overflow occurs. Storing 300 into an unsigned char reduces it modulo 256, giving 44 — a well-defined conversion for unsigned targets. "44 44" assumes the arithmetic itself is done in 8 bits.
With 32-bit int, what does this code print?
printf("%zu %zu\n", sizeof('a'), sizeof(char));- 1 1
- 4 1
- 2 1
- 1 4
In C a character constant such as 'a' has type int, so sizeof('a') == sizeof(int) — 4 here. In C++ it has type char and the answer would be 1 1, which is where the common expectation comes from. sizeof(char) is 1 by definition.
Control flow9
What does this code print?
int x = 2;
switch (x) {
case 1: printf("one ");
case 2: printf("two ");
case 3: printf("three");
break;
default: printf("other");
}
printf("\n");- two
- two three
- two three other
- one two three
switch jumps to the matching case label and then falls through all following labels until a break. Nothing stops execution after case 2, so case 3 also runs; its break then skips default. Expecting just "two" treats the cases like an if/else chain — forgetting break is one of the most common C bugs (gcc -Wimplicit-fallthrough warns about it).
What does this loop print?
for (int i = 0; i < 10; i += 3)
printf("%d ", i);- 0 3 6
- 0 3 6 9
- 3 6 9
- 0 3 6 9 12
The condition is tested before every iteration and the increment runs after the body. i takes 0, 3, 6, 9 — all less than 10 — and the loop ends when i becomes 12. "0 3 6" is an off-by-one that forgets 9 < 10; "3 6 9" wrongly assumes the increment happens before the first iteration.
What does this code print?
int x = 5;
if (x = 0)
puts("zero");
else
puts("nonzero");
printf("%d\n", x);- nonzero, then 5
- zero, then 0
- zero, then 5
- nonzero, then 0
x = 0 is an assignment, not a comparison: it stores 0 in x and the expression's value is 0, i.e. false, so the else branch runs and x is now 0. The intended test was x == 0. gcc -Wall warns "suggest parentheses around assignment used as truth value"; some programmers write 0 == x so a missing = becomes a compile error.
What does this code print?
int a = 0, b = 1;
if (a)
if (b)
puts("A");
else
puts("B");
puts("C");- Only C
- B, then C
- A, then C
- Nothing: the else is ambiguous, so it does not compile
An else always belongs to the nearest preceding if that has no else, whatever the indentation says — here it is the else of if (b). Since a is 0, the whole inner if/else is skipped and only C is printed. The indentation suggests "B, then C", which is exactly the dangling-else trap; use braces (gcc -Wdangling-else warns).
What does this code print?
int count = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
if (j == 1)
break;
count++;
}
printf("%d\n", count);- 3
- 1
- 9
- 0
break leaves only the innermost enclosing loop (or switch). Each of the 3 outer iterations counts j = 0 once and then breaks out of the inner loop, so count is 3. Answering 1 assumes break exits both loops; to leave nested loops at once you need a flag, a return, or goto.
What does this code print?
int n = 10;
do {
printf("%d\n", n);
n++;
} while (n < 5);- Nothing
- 10
- 10, then 11
- It counts up from 10 forever
A do-while loop tests its condition after the body, so the body always runs at least once: 10 is printed, n becomes 11, and 11 < 5 is false, so the loop stops. The same code written as while (n < 5) { ... } would print nothing.
What happens when this loop runs?
int i = 0;
while (i < 5) {
if (i == 2)
continue;
printf("%d ", i);
i++;
}- It prints 0 1 3 4
- It never terminates: after 0 and 1 are printed, i stays 2
- It prints 0 1 2 3 4
- It prints 0 1 and stops
continue jumps straight to the loop condition and skips the rest of the body — including i++ — so i stays 2 forever. In a for loop, continue still executes the increment expression, so for (i = 0; i < 5; i++) { if (i == 2) continue; ... } would print 0 1 3 4; expecting that is the typical mistake when rewriting a for loop as a while loop.
What happens when this loop runs?
double x[5] = {1, 2, 3, 4, 5};
double s = 0;
for (unsigned i = 4; i >= 0; i--)
s += x[i];- It sums x[4] down to x[0] and stops
- It sums x[4] down to x[1] and stops; x[0] is skipped
- It does not compile: an unsigned variable cannot be decremented
- i >= 0 is always true for unsigned, so after 0 i wraps to UINT_MAX and x is read far out of bounds
An unsigned value can never be negative, so i >= 0 is always true. After i = 0, i-- wraps around to UINT_MAX (well defined for unsigned), the loop continues and x[UINT_MAX] is an out-of-bounds read — undefined behaviour, usually a crash. gcc -Wextra warns "comparison of unsigned expression >= 0 is always true". Count down with for (unsigned i = 5; i-- > 0; ) or use a signed index.
What does this code print?
int a = 0, b = 0;
if (a++ && b++)
puts("both");
printf("%d %d\n", a, b);- 1 1
- 1 0
- 0 0
- both, then 1 1
a++ yields the old value 0, which is false, so && short-circuits and its right operand b++ is never evaluated: b stays 0, while a has been incremented to 1. && and || guarantee left-to-right evaluation and stop as soon as the result is known — the basis of guards like p != NULL && p->n > 0.
Functions9
What does this program print?
void swap(int a, int b)
{
int t = a;
a = b;
b = t;
}
int main(void)
{
int x = 1, y = 2;
swap(x, y);
printf("%d %d\n", x, y);
return 0;
}- 1 2
- 2 1
- 2 2
- It does not compile: a and b must be pointers
C passes every argument by value: swap receives copies of x and y and exchanges only the copies, which vanish when it returns. To modify the caller's variables, pass their addresses: void swap(int *a, int *b) called as swap(&x, &y). Expecting "2 1" comes from languages with reference parameters.
What does this program print?
int next_id(void)
{
static int n = 0;
return ++n;
}
int main(void)
{
next_id();
next_id();
printf("%d\n", next_id());
return 0;
}- 1
- 0
- 2
- 3
A static local variable has static storage duration: it is initialized once, before the program starts, and keeps its value between calls. The three calls return 1, 2 and 3. Answering 1 assumes "= 0" runs on every call, which is true only for an ordinary (automatic) local variable.
What does printf("%d\n", fact(5)) print?
int fact(int n)
{
return n <= 1 ? 1 : n * fact(n - 1);
}- 24
- 5
- 120
- 720
fact(5) = 5 * fact(4) = 5 * 4 * 3 * 2 * fact(1), and the base case n <= 1 returns 1, so the result is 120. 24 is 4! (stopping one level too early) and 720 is 6!. With 32-bit int this function overflows from 13! on — use double or unsigned long long for larger arguments.
In C99/C11 (unlike C++), what does the declaration int f(); mean?
- f takes no arguments, exactly like int f(void)
- f returns int and its parameters are unspecified — it is not a prototype, so calls are not checked
- f takes any number of int arguments, like int f(int, ...)
- It is a syntax error: a parameter list cannot be empty
An empty parameter list in a declaration is an old-style (K&R) declaration: it says nothing about the parameters, so a call like f(1, 2.5) compiles without a diagnostic and is undefined behaviour at run time if it does not match the definition. Write int f(void) for "no parameters". Treating () as (void) is the C++ habit; C only adopted that meaning in C23.
What does this program print?
int calls = 0;
int fib(int n)
{
calls++;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
int main(void)
{
int r = fib(5);
printf("%d %d\n", r, calls);
return 0;
}- 5 5
- 8 15
- 5 15
- 5 9
fib(5) = 5 (0, 1, 1, 2, 3, 5). The number of calls satisfies C(n) = 1 + C(n-1) + C(n-2) with C(0) = C(1) = 1, giving 1, 1, 3, 5, 9, 15. The naive double recursion recomputes the same values again and again and grows exponentially; "5 5" assumes each value is computed once, which only memoization or a simple loop achieves. "8 15" is an off-by-one in the Fibonacci indexing.
What does this program print?
void zero_first(int a[])
{
a[0] = 0;
}
int main(void)
{
int v[2] = {5, 6};
zero_first(v);
printf("%d %d\n", v[0], v[1]);
return 0;
}- 5 6
- 0 6
- 0 0
- It does not compile: arrays cannot be passed to functions
Arguments are still passed by value — but the value passed for an array is a pointer to its first element (array decay), so the function writes through that pointer into the caller's array. Arrays are never copied when passed. Declare the parameter const int a[] when the function must not modify it. "5 6" expects a copy as with a scalar.
What does static mean in this function definition at file scope?
static double norm2(const double *v, int n)
{
double s = 0;
for (int i = 0; i < n; i++)
s += v[i] * v[i];
return s;
}- norm2's local variables keep their values between calls
- norm2 is evaluated at compile time
- norm2 cannot call other functions or itself
- norm2 has internal linkage: it can only be called from the same source file
At file scope, static on a function or global variable gives it internal linkage: it is invisible to other translation units, which hides helpers and avoids name clashes between files. Inside a function body, static on a local variable means something else — static storage duration, i.e. the value survives between calls. The same keyword with two meanings is the source of the second answer.
What does this program print?
double twice(double x) { return 2 * x; }
double square(double x) { return x * x; }
double apply(double (*f)(double), double x)
{
return f(x);
}
int main(void)
{
double (*ops[2])(double) = { twice, square };
printf("%g\n", apply(ops[1], 3) + apply(ops[0], 3));
return 0;
}- 18
- 12
- It does not compile: functions cannot be stored in an array
- 15
A function name used as a value decays to a pointer to the function. ops is an array of two pointers to functions taking and returning double: ops[1] is square, giving 9, and ops[0] is twice, giving 6 — 15 in total. Passing function pointers is how C numerical routines (integrators, root finders, qsort's comparator) receive the function to work on.
Callers pass float variables, e.g. sum(2, f1, f2). What must replace /* ??? */?
#include <stdarg.h>
double sum(int n, ...)
{
va_list ap;
va_start(ap, n);
double s = 0;
for (int i = 0; i < n; i++)
s += /* ??? */;
va_end(ap);
return s;
}- va_arg(ap, double)
- va_arg(ap, float)
- (float)va_arg(ap, int)
- *(float *)ap
Arguments that match the ... undergo the default argument promotions: float becomes double, char and short become int. So the floats arrive as doubles, and va_arg(ap, float) is undefined behaviour (gcc warns that float is promoted to double when passed through ...). The same rule explains why printf uses %f for both float and double.
Pointers9
What does this code print?
int x = 10;
int *p = &x;
*p = 20;
printf("%d\n", x);- 20
- 10
- The address of x
- It does not compile: *p cannot be assigned
p holds the address of x, so *p designates x itself, and assigning to *p changes x. Answering 10 treats p as if it pointed to a copy of x. Printing an address would require printf("%p", (void *)p).
What does this code print?
int a[] = {10, 20, 30, 40};
int *p = a;
p += 2;
printf("%d %d\n", *p, *(p - 1));- 30 20
- 20 10
- 30 29
- Garbage: p += 2 moves only 2 bytes into a[0]
Pointer arithmetic counts in elements of the pointed-to type: p += 2 moves by 2 ints (8 bytes with 4-byte int), to a[2] = 30, and *(p - 1) is a[1] = 20. "30 29" mixes up *(p - 1) with *p - 1; the "2 bytes" answer is the mistake of thinking in bytes.
What does this code print?
int a[] = {1, 2, 3};
int *p = a;
int v = *p++;
printf("%d %d %d\n", v, *p, a[0]);- 1 2 2
- 2 2 1
- 2 3 1
- 1 2 1
Postfix ++ binds tighter than unary *, so *p++ means *(p++): it yields the value at the old p (1) and moves p to a[1]. The array itself is not changed. "1 2 2" reads it as (*p)++, which would increment a[0]; "2 2 1" is what *++p would give.
Which statement, added after these declarations, does NOT compile?
int x = 1, y = 2;
const int *p = &x;
int *const q = &x;- p = &y;
- *q = 5;
- *p = 5;
- x = 5;
Read declarations from right to left: p is a pointer to const int — you cannot modify the target through p, but p itself may be re-pointed. q is a const pointer to int — *q = 5 is fine, but q = &y would fail. x itself is not const: const int * only promises not to modify it through p. Mixing up which part the const applies to is the typical mistake.
What does this code print?
int a[5] = {1, 2, 3, 4, 5};
int *p = (int *)(&a + 1);
printf("%d\n", *(p - 1));- 2
- 5
- 1
- It crashes: &a + 1 points outside the array
&a has type int (*)[5], a pointer to the whole array, so &a + 1 advances by sizeof a (20 bytes) to just past the end of the array — a valid one-past-the-end pointer as long as it is not dereferenced. Converted to int *, p - 1 points to the last element, 5. Answering 2 treats &a + 1 like a + 1, which advances by one int.
What does this code print?
int x = 3;
int *p = &x;
int **pp = &p;
**pp = 7;
printf("%d\n", x);- 3
- 7
- The address of x
- It does not compile: a pointer cannot point to another pointer
pp points to p, so *pp is p and **pp is x itself; the assignment sets x to 7. Pointers to pointers are common in C: a function that must change the caller's pointer (e.g. allocate a buffer and return it through a double ** parameter) takes one, and char **argv is a pointer to an array of strings.
What are the types of p and q after this declaration?
int* p, q;- Both p and q are pointers to int
- Both are plain ints; the * is ignored
- p is a pointer to int, q is a plain int
- It does not compile: the * must be written next to the variable name
The * belongs to the declarator, not to the type: int* p, q; means exactly int *p, q;. Spacing does not matter to the compiler, but writing int* suggests the wrong reading. Declare int *p, *q; or one variable per line.
What does this code print?
double d[10];
double *a = &d[2];
double *b = &d[7];
printf("%td\n", b - a);- 40
- -5
- 5
- It does not compile: pointers cannot be subtracted
Subtracting two pointers into the same array gives the distance in elements, not bytes, as a ptrdiff_t (printed with %td): 7 - 2 = 5. 40 is the distance in bytes (5 * sizeof(double)). The subtraction is only defined for pointers into the same array (or one past its end).
What does this code print?
int a[] = {1, 2, 3};
int *p = a + 1;
printf("%d %d\n", p[-1], 2[a]);- 2 3
- Nothing definite: a negative index is undefined behaviour
- It does not compile: 2[a] is not valid syntax
- 1 3
E1[E2] is defined as *((E1) + (E2)). So p[-1] is *(p - 1) = a[0] = 1 — a negative index is fine as long as the address stays inside the array. 2[a] is *(2 + a), and addition commutes, so it is a[2] = 3: legal, though nobody should write it. "2 3" overlooks the -1 and reads p[-1] as *p, which is a[1].
Arrays and strings9
What does this code print?
char s[] = "hello";
printf("%zu %zu\n", sizeof s, strlen(s));- 6 5
- 5 5
- 5 6
- 8 5
A string literal includes a terminating '\0', so the array s has 6 elements, while strlen counts the characters before the '\0': 5. "8 5" is what you would get on a 64-bit system with char *s = "hello", where sizeof gives the size of the pointer.
On a typical 64-bit platform (8-byte pointers, 4-byte int), what does this program print?
void f(int a[])
{
printf("%zu\n", sizeof a / sizeof a[0]);
}
int main(void)
{
int v[10];
printf("%zu\n", sizeof v / sizeof v[0]);
f(v);
return 0;
}- 10, then 10
- 10, then 1
- 10, then 2
- 40, then 8
In a parameter list int a[] means int *a: an array argument decays to a pointer to its first element. Inside f, sizeof a is the size of a pointer (8), and 8 / 4 = 2. The sizeof trick only works where the array itself is in scope — pass the length as a separate parameter (gcc warns with -Wsizeof-array-argument). "40, then 8" forgets the division.
What does this code print?
char a[] = "abc";
char b[] = "abc";
printf("%d %d\n", a == b, strcmp(a, b) == 0);- 1 1
- 1 0
- 0 0
- 0 1
In a == b both arrays decay to pointers to their first elements; a and b are two distinct arrays, so the addresses differ and the result is 0. strcmp compares the characters and returns 0 when they are equal. Comparing strings with == is the classic mistake — with two pointers to identical literals it may even appear to work, because compilers may merge identical literals.
What does buf contain after this call?
char buf[4];
strncpy(buf, "hello", sizeof buf);- "hel" followed by '\0', because strncpy always terminates the copy
- "hello", because strncpy enlarges the buffer as needed
- 'h', 'e', 'l', 'l' with no terminating '\0' — it is not a valid string
- Nothing: strncpy refuses to copy when the source is too long
strncpy(dst, src, n) copies at most n characters and adds '\0' only if src is shorter than n. Here exactly 4 characters are copied and no terminator is written, so strlen(buf) or printf("%s", buf) would read past the array (undefined behaviour). Safe alternatives: snprintf(buf, sizeof buf, "%s", src), which truncates to "hel" and terminates, or setting buf[sizeof buf - 1] = '\0' after strncpy with n = sizeof buf - 1.
What does this code print?
int a[5] = {1, 2};
printf("%d %d %d\n", a[1], a[2], a[4]);- 2 followed by two unpredictable values
- 1 0 0
- 2 0 0
- It does not compile: the initializer has too few values
When an initializer list is shorter than the array, the remaining elements are initialized to zero — even for a local array. So int a[100] = {0}; is the usual way to zero an array. Only an array with no initializer at all has indeterminate contents. "1 0 0" forgets that indexing starts at 0.
What does this code print?
printf("%zu %zu\n", strlen("abc\0def"), sizeof "abc\0def");- 7 8
- 3 8
- 3 4
- 7 7
strlen stops at the first '\0', so it returns 3. sizeof a string literal counts every character plus the implicit terminator: 7 + 1 = 8. This is why the str* functions cannot handle binary data that contains zero bytes — use memcpy and explicit lengths for that.
What happens here?
char *s = "hello";
s[0] = 'H';
puts(s);- It prints Hello
- It prints hello, because the assignment changes a copy
- It does not compile: s[0] cannot be assigned through a char *
- Undefined behaviour: string literals must not be modified (often a crash, as they live in read-only memory)
A string literal is a static array that must not be modified. In C its type is char[] (not const char[] as in C++), so the compiler accepts the assignment without complaint, but the program typically crashes because the literal is in read-only memory. char s[] = "hello"; creates a modifiable copy; declaring const char *s makes the mistake a compile error.
What is wrong with this code?
char name[8];
strcpy(name, "Christine");- Buffer overflow (undefined behaviour): "Christine" needs 10 bytes including the terminating '\0'
- Nothing serious: strcpy truncates the copy to "Christi" plus '\0'
- name holds "Christin" without '\0', otherwise it is safe
- It does not compile: the string is longer than the array
strcpy knows nothing about the size of the destination: it copies 9 letters plus '\0' — 10 bytes into an 8-byte array — and overwrites whatever lies after it. Forgetting the room for '\0' makes it worse. Check strlen(src) < sizeof name first, or use snprintf(name, sizeof name, "%s", src), which truncates and always terminates. Compilers may warn, but they do not refuse.
Is this declaration valid C, and what does s contain?
char s[5] = "hello";- Valid in C: s holds the 5 characters h e l l o with no terminating '\0', so it is not a string
- Valid: the compiler enlarges s to 6 elements to fit the '\0'
- Invalid: the initializer is too long, so it does not compile
- Valid: s holds "hell" followed by '\0'
C (unlike C++) allows a string literal to initialize an array that has room for exactly its characters; the terminating '\0' is then silently dropped. s is a fine char array, but passing it to strlen or printf("%s") reads past its end — undefined behaviour. Omit the size (char s[] = "hello";) and let the compiler count, including the '\0'.
Memory management9
Which standard function allocates memory and sets all of its bytes to zero?
- malloc
- realloc
- calloc
- alloca
calloc(n, size) allocates n * size bytes and fills them with zero bits, which means 0 for integers and 0.0 for IEEE doubles. malloc leaves the contents indeterminate — reading before writing is a common bug. realloc does not clear the newly added part, and alloca is not standard C at all (it allocates on the stack).
What is wrong with this code?
double *p = malloc(100 * sizeof *p);
p = malloc(200 * sizeof *p);
free(p);- The first block is leaked: its only pointer was overwritten before it was freed
- Nothing: the second malloc automatically frees the first block
- Nothing: free(p) releases both blocks
- sizeof *p dereferences an uninitialized pointer
Every malloc returns a new block, and C has no garbage collector. After the second assignment nothing points to the first block, so it can never be freed — a memory leak. free releases exactly one block. sizeof *p is not evaluated at run time (it only uses the type), so it is safe and in fact the recommended idiom. valgrind or -fsanitize=address report such leaks.
What is the problem with the realloc line?
double *v = malloc(n * sizeof *v);
/* ... fill v ... */
v = realloc(v, 2 * n * sizeof *v);- realloc frees the old block even when it fails, so v dangles
- realloc does not preserve the old contents, so the data is lost
- realloc can only shrink a block, never grow it
- If realloc fails it returns NULL, v is overwritten and the original block is leaked
On failure realloc returns NULL and leaves the old block untouched — but assigning the result straight to v loses the only pointer to it. Use a temporary: double *t = realloc(v, ...); if (t == NULL) { /* handle, v still valid */ } else v = t;. On success the contents are preserved up to the smaller of the two sizes, although the block may move.
What happens here?
int *p = malloc(sizeof *p);
*p = 42;
free(p);
if (p != NULL)
printf("%d\n", *p);- It prints 42, because free only marks the memory as reusable
- It prints nothing, because free sets p to NULL
- It prints 0, because free clears the memory
- Undefined behaviour: free does not set p to NULL, so *p reads freed memory
free receives a copy of the pointer and cannot change p; afterwards p is a dangling pointer and reading *p is a use-after-free — undefined behaviour. It may well print 42 in a test run, which is exactly why such bugs survive. A common defensive habit is to write p = NULL; right after free(p).
Assume realloc succeeds. What about the assignment *mid = 5?
int *a = malloc(4 * sizeof *a);
int *mid = a + 2;
int *t = realloc(a, 100000 * sizeof *a);
if (t != NULL) {
a = t;
*mid = 5;
}- It sets a[2] = 5, because realloc always grows a block in place
- It sets a[2] = 5, because realloc updates every pointer into the block
- It is fine as long as the new size is larger than the old one
- Undefined behaviour: the block may have moved, and mid still points into the old one
realloc may allocate a new block, copy the data and free the old one, so every pointer into the old block becomes invalid. Nothing can update such pointers automatically. Keep indices instead of pointers into a growing array, or recompute them after realloc: mid = a + 2;. This bug is common in dynamic arrays that hand out element pointers.
What does malloc return when it cannot allocate the requested memory?
- A pointer to a zero-sized block
- Nothing: it terminates the program with an "out of memory" message
- A null pointer
- Nothing: it throws an exception that the caller can catch
malloc, calloc and realloc report failure by returning NULL; C has no exceptions, so checking is the caller's job: if (p == NULL) { ... }. Large numerical arrays (e.g. n * n doubles for a matrix) are where allocations really fail, and dereferencing the unchecked NULL then crashes far from the cause.
p was set by a successful int *p = malloc(10 * sizeof *p); and not yet freed. Which call is guaranteed to be safe?
- free(p + 1);
- free(p); free(p);
- free(NULL);
- int a[10]; free(a);
free(NULL) does nothing by definition, so cleanup code may free pointers that might be NULL without checking. free must receive exactly a pointer returned by malloc/calloc/realloc (not p + 1), only once (a double free corrupts the heap — undefined behaviour), and never memory that did not come from the heap, such as a local array. Setting p = NULL after free(p) turns an accidental second free into a harmless free(NULL).
What is wrong with this function?
double *make_vector(int n)
{
double v[100];
for (int i = 0; i < n; i++)
v[i] = 0.0;
return v;
}- Nothing: arrays are always allocated on the heap
- Nothing: the array is copied to the caller because it is returned
- Nothing, as long as the caller uses the result before calling another function
- v is a local array that ceases to exist when the function returns, so the caller gets a dangling pointer
A local array has automatic storage duration: its lifetime ends at return, and any use of the returned pointer is undefined behaviour (gcc warns "function returns address of local variable" and may even return NULL on purpose). Allocate with malloc(n * sizeof(double)) and let the caller free it, or let the caller pass in the buffer. The last answer describes the "it seemed to work in my test" illusion.
What is wrong with this function?
char *dup(const char *t)
{
char *s = malloc(strlen(t));
if (s != NULL)
strcpy(s, t);
return s;
}- Nothing: strlen counts the terminating '\0' too
- The result of malloc must be cast to (char *) in C
- The buffer is one byte too small: strcpy also writes the terminating '\0', a heap overflow
- strcpy needs the length as a third argument
strlen does not count the '\0', so the allocation must be strlen(t) + 1. Writing one byte past a malloc'ed block is undefined behaviour that often goes unnoticed because allocators round sizes up — AddressSanitizer reports it immediately. In C the void * returned by malloc converts implicitly, so no cast is needed (C++ is different). POSIX/C23 strdup does this correctly.
Structs and unions9
Given these declarations, which expression is equivalent to p->x?
struct point { int x, y; };
struct point a = {1, 2};
struct point *p = &a;- *p.x
- p.x
- (*p).x
- &p.x
-> is shorthand for "dereference, then select the member": p->x is (*p).x. Without the parentheses, *p.x parses as *(p.x) because . binds tighter than unary *, and p.x is invalid because p is a pointer, not a struct. Rule: . for struct objects, -> for pointers to structs.
On a typical platform where int is 4 bytes and 4-byte aligned, what does this print?
struct rec {
char c;
int i;
char d;
};
printf("%zu\n", sizeof(struct rec));- 6
- 9
- 12
- 8
The compiler inserts padding so that i starts at a multiple of 4: c at offset 0, 3 padding bytes, i at 4–7, d at 8, then 3 trailing padding bytes so the total is a multiple of the alignment (so that i stays aligned in an array of struct rec). 6 ignores padding entirely, 9 forgets the trailing padding; reordering the members as int, char, char gives 8.
With 4-byte int and 8-byte, 8-aligned double, what does this print?
union value {
int i;
double d;
char tag[3];
};
printf("%zu\n", sizeof(union value));- 15
- 16
- 8
- 3
All members of a union start at the same address and share the same storage, so its size is the size of the largest member (8) rounded up to the strictest member alignment (8): 8. Summing the member sizes (15 or 16) is struct thinking. Only the member written last holds a meaningful value at any time.
With an 8-byte double aligned on 8 bytes, what does this print?
struct a { char c1; double d; char c2; };
struct b { double d; char c1; char c2; };
printf("%zu %zu\n", sizeof(struct a), sizeof(struct b));- 10 10
- 16 16
- 24 16
- 24 24
struct a: c1 at 0, 7 padding bytes, d at 8–15, c2 at 16, then 7 trailing bytes to a multiple of 8 — 24. struct b: d at 0–7, c1 at 8, c2 at 9, 6 trailing bytes — 16. Members are never reordered by the compiler, so declaring them from largest to smallest alignment minimizes padding, which matters for big arrays of records. "24 24" assumes member order does not matter.
What does this code print?
struct point { int x, y, z; };
struct point p = { .z = 5 };
printf("%d %d %d\n", p.x, p.y, p.z);- 5 0 0
- 0 0 5
- Two unpredictable values, then 5
- It does not compile: designated initializers exist only in C++
C99 designated initializers name the member they set, so .z = 5 sets z regardless of position. Members not mentioned in an initializer are initialized to zero, even for local variables. C had designated initializers long before C++20, which added a more restricted version.
What does this code print?
struct vec { double a[3]; };
struct vec x = { {1.0, 2.0, 3.0} };
struct vec y = x;
y.a[0] = 9.0;
printf("%g %g\n", x.a[0], y.a[0]);- 9 9
- 1 9
- 1 1
- It does not compile: arrays cannot be copied
Struct initialization and assignment copy every member, including arrays inside the struct — even though a bare array cannot be assigned. y is an independent copy, so changing it leaves x alone. "9 9" assumes reference semantics. Note that the copy is shallow: if a struct contains a pointer, only the pointer is copied, not the data it points to.
What happens with this code?
struct point { int x, y; };
struct point a = {1, 2}, b = {1, 2};
if (a == b)
puts("equal");- It does not compile: == is not defined for structures
- It prints equal
- It prints nothing, because == compares the addresses of a and b
- It compares the structs byte by byte, including padding
C has no comparison operators for structs; compare the members yourself, e.g. a.x == b.x && a.y == b.y, typically in a small helper function. memcmp(&a, &b, sizeof a) is not a reliable substitute, because it also compares padding bytes, whose contents are unspecified.
Why is the member next declared as struct node * instead of Node *?
typedef struct node {
double value;
struct node *next;
} Node;- Node * would make next a copy of the whole node rather than a pointer
- Members of a struct can never use typedef names
- struct node * makes next point to the node itself automatically
- The typedef name Node does not exist until the end of the declaration, but the tag struct node is already in scope
The tag struct node becomes visible as soon as it is written, so a pointer to that (still incomplete) type is allowed inside its own definition, whereas Node is declared only when the whole typedef is complete. Alternatively write typedef struct node Node; first and then use Node * inside the struct. A struct can never contain itself by value (its size would be infinite), only a pointer to itself.
How do you allocate a struct series whose data member can hold n values?
struct series {
size_t n;
double data[];
};- malloc(sizeof(struct series) + n * sizeof(double))
- malloc(n * sizeof(struct series))
- malloc(n * sizeof(double)), because data is the only array
- struct series s = { n }; — data is sized automatically
data[] is a C99 flexible array member: an incomplete array as the last member that adds nothing (apart from possible padding) to sizeof(struct series). You allocate the header plus the space for the elements in a single block, which means one malloc, one free and good locality. Allocating only n doubles forgets the header; such a struct cannot be given its element storage as an ordinary variable.
Preprocessor9
What does this code print?
#define SQUARE(x) x * x
printf("%d\n", SQUARE(1 + 2));- 9
- 3
- 5
- It does not compile: a macro argument cannot contain an operator
Macros substitute tokens before compilation, without regard to precedence: SQUARE(1 + 2) becomes 1 + 2 * 1 + 2, which is 5. Expecting 9 is the classic mistake. Define it as #define SQUARE(x) ((x) * (x)) — parentheses around every parameter and the whole body. Even then SQUARE(i++) evaluates i++ twice; a static inline function avoids both problems.
What is the purpose of the #ifndef / #define / #endif lines in this header vector.h?
#ifndef VECTOR_H
#define VECTOR_H
typedef struct { double x, y, z; } vec3;
double dot(vec3 a, vec3 b);
#endif- They stop the header from being included in more than one .c file of the program
- A second #include of the header in the same source file expands to nothing, so nothing is defined twice
- They make the compiler compile the header only once and cache the result
- They declare VECTOR_H as a global variable that other files can test
These are include guards. The first inclusion defines VECTOR_H; any later inclusion in the same translation unit (directly or through other headers) skips the whole body, so the typedef is not repeated (a redefinition error in C99/C11). They work per translation unit: every .c file that includes the header still gets the declarations, which is what you want. #pragma once is a widespread non-standard alternative.
What is the conventional difference between #include <stdio.h> and #include "matrix.h"?
- <...> works only for the C standard headers; your own headers can never be included with it
- The "..." form first looks for the file relative to the including source file, then falls back to the paths searched by <...>
- "..." includes the file at link time, <...> at compile time
- There is none: both forms search exactly the same directories in the same order
Both forms do the same thing — paste the file's text in during preprocessing; only the search order differs (implementation-defined, but conventionally "..." starts in the directory of the current file). <...> is for system and library headers, and with -I your own directories are searched by both forms. Nothing is included at link time: the linker deals with object files and libraries such as -lm, not headers.
What does this code print?
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int i = 5, j = 3;
int m = MAX(i++, j);
printf("%d %d\n", m, i);- 5 6
- 6 6
- Undefined behaviour: i is modified twice without a sequence point
- 6 7
The macro expands to ((i++) > (j) ? (i++) : (j)). The condition compares 5 > 3 and increments i to 6; there is a sequence point after the first operand of ?:, so the second i++ is well defined: it yields 6 and leaves i = 7. "5 6" is what a function max(i++, j) would give. A macro evaluates an argument as many times as it appears — another reason to prefer static inline functions.
When is a macro such as #define N 100 replaced in the code?
- At run time, when the line is executed
- At link time, when the object files are combined
- During preprocessing, as token substitution, before the compiler proper sees the code
- During compilation, after type checking, like a const variable
Preprocessing is the first translation phase: every token N is replaced by 100 before the code is parsed. Macros therefore have no type and no scope (they are visible from the #define to the end of the file or an #undef), and the debugger does not know them. gcc -E shows the preprocessed output.
The program is compiled with gcc prog.c -o prog (no other flags). What does it print?
#include <stdio.h>
int main(void)
{
#ifdef DEBUG
puts("checking input");
#endif
puts("done");
return 0;
}- checking input, then done
- Nothing
- done
- It does not compile: DEBUG is not defined
#ifdef DEBUG tests whether a macro named DEBUG is defined. It is not, so the preprocessor removes the lines up to #endif and only "done" is printed. Compiling with -DDEBUG (which defines DEBUG as 1) would include them. An undefined macro is not an error here — testing for it is exactly what #ifdef is for.
Why does this code fail to compile?
#define PI 3.14159;
double area(double r)
{
return PI * r * r;
}- PI is already defined in math.h, so redefining it is an error
- Macros cannot be used inside functions
- An object-like macro name must be followed by parentheses
- The semicolon is part of the macro, so the line becomes return 3.14159; * r * r; and * r * r; is invalid
Everything after the macro name is replacement text, the semicolon included. After substitution the statement return 3.14159; is followed by * r * r;, which applies unary * to a double. Write #define PI 3.14159, or better a typed constant. Standard C's math.h defines no PI at all (M_PI is a POSIX extension).
What does this code print?
#define STR(x) #x
#define XSTR(x) STR(x)
#define N 42
printf("%s %s\n", STR(N), XSTR(N));- 42 42
- N N
- N 42
- 42 N
The # operator turns its argument into a string literal without macro-expanding it first, so STR(N) is "N". Arguments that are not used with # or ## are fully expanded before substitution, so XSTR(N) becomes STR(42) and then "42". This two-level trick is the standard way to stringize the value of a macro, e.g. a version number.
What does this code print?
#define SWAP(a, b) t = a; a = b; b = t
int x = 1, y = 2, t = 0;
if (x > y)
SWAP(x, y);
printf("%d %d\n", x, y);- 1 2
- 2 1
- It does not compile: a macro cannot expand to several statements
- 2 0
The macro expands to if (x > y) t = x; x = y; y = t; — only the first statement belongs to the if. The condition is false, so t stays 0, but x = y and y = t run unconditionally, giving 2 0. Expecting "1 2" is the trap. Wrap multi-statement macros in do { ... } while (0), or use a function.
Standard library and I/O9
Which call correctly reads a number into the variable double d;?
- scanf("%f", &d);
- scanf("%lf", &d);
- scanf("%lf", d);
- scanf("%d", &d);
scanf needs the address of the object, and the conversion must match the pointed-to type: %f expects a float *, %lf a double *, %d an int *. A mismatch is undefined behaviour and typically stores garbage; forgetting & passes the value instead of a pointer. Note the asymmetry with printf, where %f and %lf both print a double, because a float argument is promoted to double.
On Linux, gcc solve.c -o solve fails with "undefined reference to 'sqrt'", although solve.c contains #include <math.h>. Why?
- The header only declares sqrt; the math library itself must be linked with -lm, placed after the source file
- math.h must be included before stdio.h
- sqrt exists only when compiling with -std=c99
- The argument of sqrt must be cast to double
"Undefined reference" is a linker error: the header gave the compiler the declaration, but the definition lives in libm, which GNU toolchains do not link by default. Use gcc solve.c -o solve -lm — libraries go after the files that need them. The error may appear only sometimes, because gcc can compute sqrt of a constant at compile time; some platforms (macOS, Windows) link the math functions automatically.
What does this code print?
printf("[%8.3f]\n", 3.14159);- [ 3.142]
- [3.142 ]
- [ 3.14]
- [3.14159 ]
In %8.3f, 8 is the minimum field width and .3 the number of digits after the decimal point (with rounding): "3.142" is 5 characters, padded on the left with 3 spaces. Left alignment needs the - flag (%-8.3f). "[ 3.14]" treats the precision as significant digits, which is what %8.3g would do.
nums.txt contains the line "1 2 3" followed by a newline. What does this code print?
FILE *f = fopen("nums.txt", "r");
int x, sum = 0;
while (!feof(f)) {
fscanf(f, "%d", &x);
sum += x;
}
printf("%d\n", sum);
fclose(f);- 6
- 3
- Nothing: it loops forever
- 9
feof becomes true only after a read has tried to go past the end of the file. After 3 is read, the newline is still unread, so feof is false and the loop runs again: fscanf hits the end, returns EOF and leaves x unchanged, and 3 is added a second time. Test the read itself instead: while (fscanf(f, "%d", &x) == 1) sum += x;. (Real code should also check that fopen did not return NULL.)
What does this code print?
printf("%d%%\n", 50);- 50%%
- 50
- %d%
- 50%
In a printf format % starts a conversion specification, and %% is the conversion that prints a single literal percent sign. So %d prints 50 and %% prints %. A lone % at the end of a format is invalid (undefined behaviour), which is why the doubled form exists.
What happens to an existing file data.txt when it is opened with fopen("data.txt", "w")?
- Its contents are erased (truncated to length zero)
- New output is appended at the end of the old contents
- fopen fails because the file already exists
- The old contents are kept and overwritten byte by byte from the start
Mode "w" creates the file or truncates an existing one to zero length. "a" appends to the end, "r+" opens an existing file for reading and writing without truncating it (overwriting in place), and C11's "wx" fails if the file already exists — use it to avoid destroying data.
What does this code print?
int n = printf("x=%d\n", 42);
printf("%d\n", n);- x=42, then 4
- x=42, then 5
- x=42, then 1
- x=42, then 0
printf returns the number of characters it wrote: 'x', '=', '4', '2' and the newline — 5 (a negative value signals an output error). "4" forgets the newline; 1 or 0 confuses printf with a success flag or with scanf, which returns the number of items assigned.
The user types abc and presses Enter. What does this code print?
char buf[16];
fgets(buf, sizeof buf, stdin);
printf("%zu\n", strlen(buf));- 4
- 3
- 16
- 5
fgets stops after the newline and keeps it in the buffer, so buf holds "abc\n" and strlen returns 4. That is why strcmp(buf, "abc") fails after fgets; strip the newline with buf[strcspn(buf, "\n")] = '\0';. 16 is the buffer size, not the string length. Unlike gets (removed in C11), fgets never writes more than sizeof buf bytes.
The user types 5, presses Enter, then types hello and presses Enter. What does line contain afterwards?
int n;
char line[64];
scanf("%d", &n);
fgets(line, sizeof line, stdin);- "hello\n"
- "5\nhello\n"
- Only "\n" — the newline left in the input by scanf
- An empty string "", because scanf consumed the whole line
%d skips leading whitespace, reads 5 and stops at the first character that cannot be part of a number — the newline, which stays in the input. fgets then reads up to and including the next newline, so it returns at once with just "\n". Either discard the rest of the line after scanf (int c; while ((c = getchar()) != '\n' && c != EOF);) or read every line with fgets and parse it with sscanf or strtol.
Undefined behavior9
What does this code print?
int i = 1;
i = i++ + 1;
printf("%d\n", i);- 2
- 3
- 1
- Nothing definite: the behaviour is undefined
i is modified twice — by ++ and by the assignment — and in C the side effect of i++ is unsequenced relative to the assignment, so the behaviour is undefined (C++17 changed the rules for this case, C did not). Different compilers or optimization levels may print 2 or 3; gcc -Wall warns "operation on 'i' may be undefined". Write what you mean: i = i + 2; or two separate statements.
What does this code print?
int a[3] = {1, 2, 3};
printf("%d\n", a[3]);- 0, because elements past the end read as zero
- 3, because a[3] is the last element
- The program stops with an "index out of range" error
- Nothing definite: a[3] is past the end of the array, so the behaviour is undefined
The valid indices of int a[3] are 0, 1 and 2. C performs no bounds checking: reading a[3] is undefined behaviour — it may print garbage, crash, or seem to work. "3" is the 1-based-index mistake. Tools such as -fsanitize=address catch out-of-bounds accesses during testing.
Why may gcc -O2 compile this function to simply "return 0"?
int will_overflow(int x)
{
return x + 1 < x;
}- Signed overflow is undefined, so the compiler may assume x + 1 never wraps, which makes x + 1 < x always false
- Because int becomes 64 bits wide at -O2, so x + 1 cannot wrap
- Because the comparison is removed only when x is a compile-time constant
- It may not: the standard requires x + 1 to wrap to INT_MIN, so the function must return 1 for INT_MAX
Because signed integer overflow is undefined behaviour, the optimizer may reason as if ints were mathematical integers, where x + 1 < x is never true. Test before the operation instead: x == INT_MAX, or use unsigned arithmetic (defined to wrap modulo 2^N), __builtin_add_overflow, or C23 ckd_add. gcc's -fwrapv makes signed overflow wrap, but that is not standard C.
What does this code print?
double v[4] = {1.0, 2.0, 3.0, 4.0};
double sum;
for (int i = 0; i < 4; i++)
sum += v[i];
printf("%g\n", sum);- 10, because local variables start at zero
- 10, because double variables are always initialized to 0.0
- It does not compile: sum must be initialized
- Nothing definite: sum is never initialized, so the result is unpredictable
Local (automatic) variables are not initialized; their value is indeterminate and using it is undefined behaviour — it may print 10 in one build and garbage in another. Only static and global variables are zero-initialized. Write double sum = 0.0;. -Wall (-Wuninitialized / -Wmaybe-uninitialized) often catches this, especially with optimization on.
What does this code print?
int i = 1;
printf("%d %d\n", i++, i++);- 1 2
- Nothing definite: i is modified twice in unsequenced arguments, so the behaviour is undefined
- 2 1
- 1 1
The order in which function arguments are evaluated is unspecified, and the two modifications of i are unsequenced relative to each other — that makes the behaviour undefined, not merely "one of the two orders". The commas between arguments are not the comma operator and provide no sequence point. Real compilers do print different results; gcc -Wall warns (-Wsequence-point).
What happens here?
int *p = NULL;
*p = 5;- Undefined behaviour; on most systems the program crashes (e.g. segmentation fault)
- It stores 5 at address 0, which is reserved for such writes
- Nothing: writes through a null pointer are ignored
- It does not compile: NULL cannot be dereferenced
A null pointer points to no object, and dereferencing it is undefined behaviour. Operating systems usually leave address 0 unmapped, so the write traps. The compiler cannot reject it in general, and the optimizer may even assume p is non-null after the dereference and delete later NULL checks. Check pointers (especially malloc results) before use.
Assume 32-bit int. Which of these expressions has well-defined behaviour?
- UINT_MAX + 1u, which is 0
- INT_MAX + 1, which is INT_MIN
- -INT_MIN, which is INT_MIN
- 1 << 31, which is INT_MIN
Unsigned arithmetic is defined modulo 2^N, so UINT_MAX + 1u wraps to 0. A signed result that does not fit is undefined behaviour: INT_MAX + 1, and -INT_MIN (INT_MAX is only 2147483647). 1 << 31 shifts a 1 into the sign bit of an int, also undefined in C99/C11 — write 1u << 31. The "results" listed are what two's-complement hardware typically produces, which is why such bugs go unnoticed until the optimizer exploits them.
With 32-bit float and unsigned int, which statement copies the bit pattern of f into bits with well-defined behaviour?
float f = 1.0f;
unsigned int bits;- bits = *(unsigned int *)&f;
- memcpy(&bits, &f, sizeof bits);
- bits = (unsigned int)f;
- bits = *(unsigned int *)(void *)&f;
Reading a float object through an unsigned int lvalue violates the strict aliasing rule (C11 6.5p7) — undefined behaviour that optimizers at -O2 really rely on; going through void * does not change the type of the access. (unsigned int)f converts the value (1.0 becomes 1), not the bits. memcpy is defined, and compilers turn it into a single register move; reading another member of a union is the other sanctioned way.
What does this code print?
const int limit = 10;
int *p = (int *)&limit;
*p = 20;
printf("%d\n", limit);- 20
- 10, because writes through p are ignored
- Nothing definite: modifying an object defined const is undefined behaviour
- It does not compile: a cast cannot remove const
An explicit cast may remove const, so the code compiles, but modifying an object that was defined const is undefined behaviour. The compiler may place it in read-only memory (crash) or substitute 10 directly, so the program can print 10 although the memory holds 20. Casting away const is only safe when the object itself was not defined const.
Numerics in C10
What does this code print?
printf("%d\n", 0.1 + 0.2 == 0.3);- 1
- 0
- It does not compile: == cannot compare doubles
- Nothing definite: comparing doubles with == is undefined behaviour
0.1, 0.2 and 0.3 have no exact binary representation. The sum of the nearest doubles to 0.1 and 0.2 is 0.30000000000000004, while the nearest double to 0.3 is 0.29999999999999998, so == gives 0. Comparing doubles with == is perfectly legal and exact — the problem is the values. Compare computed results with a tolerance.
What does this code print?
float f = 0.1f;
double d = 0.1;
printf("%d\n", f == d);- 1
- 0
- It does not compile: a float cannot be compared with a double
- 1 on 32-bit systems and 0 on 64-bit systems
For the comparison f is converted to double, but it holds the nearest float to 0.1 (0.100000001490116...), which differs from the nearest double (0.1000000000000000055...). Rounding to float's 24-bit significand lost information that converting back cannot restore. Comparing a float variable with a double literal is a typical bug — use 0.1f, or keep everything in double.
Which test is the most robust way to check that two computed doubles a and b are equal "up to rounding errors"?
- a == b
- fabs(a - b) <= 1e-9 * fmax(fabs(a), fabs(b))
- a - b < 1e-9
- (int)a == (int)b
Rounding errors scale with the magnitude of the values, so the tolerance should be relative: near 1e20 adjacent doubles are about 16000 apart, near 1e-12 an absolute tolerance of 1e-9 accepts almost anything. a - b < 1e-9 without fabs is true whenever a < b, and truncating to int ignores the fraction completely. For values that may be exactly zero, combine the relative test with a small absolute one.
With IEEE 754 single-precision float, what does this code print?
int n = 16777217; /* 2^24 + 1 */
float f = n;
printf("%d\n", (int)f);- 16777217
- 16777216
- 16777218
- Nothing definite: the value does not fit in a float, so the behaviour is undefined
float has a 24-bit significand, so it represents every integer exactly only up to 2^24 = 16777216. 2^24 + 1 lies exactly between the neighbouring floats 16777216 and 16777218, and round-to-nearest-even picks 16777216. The conversion is not undefined: the value is within float's range, it is merely rounded. A double (53-bit significand) would hold it exactly.
For general scientific computing in C, why is double usually preferred over float?
- double carries about 15–16 significant decimal digits versus about 7 for float, so rounding errors build up far more slowly
- double is an integer type with a larger range
- math.h does not support float values
- double represents decimal fractions such as 0.1 exactly
IEEE 754 double (binary64) has a 53-bit significand (DBL_DIG = 15), float (binary32) only 24 bits (FLT_DIG = 6). Floating constants such as 0.1 are double, and the classic math.h functions take double (sqrtf etc. are the float variants). float is chosen when memory or bandwidth matters, e.g. huge arrays or GPUs. Neither type stores 0.1 exactly.
What does this code print?
double x = NAN;
printf("%d %d %d\n", x == x, x != x, isnan(x) != 0);- 1 0 1
- 1 0 0
- 0 1 1
- 0 0 1
NaN is unordered with respect to everything, itself included: x == x is false and x != x is true. x != x is a well-known NaN test, but isnan() is clearer and keeps working under -ffast-math, which lets the compiler assume NaNs never occur. NaNs arise from 0.0 / 0.0, sqrt(-1.0), inf - inf and similar operations.
What does this code print (#include <math.h>)?
printf("%d %.1f %.1f\n", (int)-2.7, floor(-2.7), round(-2.7));- -2 -3.0 -3.0
- -3 -3.0 -3.0
- -2 -2.0 -3.0
- -3 -2.0 -2.0
Converting a double to int truncates toward zero, so -2.7 becomes -2; floor rounds toward minus infinity (-3), and round goes to the nearest integer, halves away from zero (-3). Truncation and floor differ for negative numbers — a typical bug when computing a grid cell index as (int)(x / h) for negative x.
With IEEE 754 single-precision float (e.g. x86-64), what does this code print?
float s = 0.0f;
for (int i = 0; i < 20000000; i++)
s += 1.0f;
printf("%.0f\n", s);- 16777216
- 20000000
- 19999999
- inf
Once s reaches 2^24 = 16777216, adjacent floats are 2 apart, and 16777216 + 1 rounds back to 16777216 (ties to even), so the sum stops growing. Long float accumulations lose precision like this; accumulate in double (exact for integers up to 2^53) or use Kahan or pairwise summation. Overflow to inf would need values around 3.4e38.
On a platform with IEEE 754 arithmetic, what does this code print?
double z = 0.0;
printf("%f %f\n", 1.0 / z, -1.0 / z);- Nothing: the program crashes with a division-by-zero error
- 0.000000 0.000000
- nan nan
- inf -inf
With IEEE 754 floating point (C Annex F, all mainstream platforms), dividing a nonzero number by zero gives an infinity with the appropriate sign; only 0.0 / 0.0 gives NaN. Integer division by zero, in contrast, is undefined behaviour and usually kills the program (SIGFPE). Detect such values with isinf / isfinite.
What does this code print?
double x = 1e-17;
printf("%g %g\n", (1.0 + x) - 1.0, x + (1.0 - 1.0));- 1e-17 1e-17
- 0 0
- 1e-17 0
- 0 1e-17
The spacing of doubles near 1.0 is about 2.2e-16 (DBL_EPSILON), so 1.0 + 1e-17 rounds back to exactly 1.0 and subtracting 1.0 leaves 0. In the second expression 1.0 - 1.0 is computed first, so x survives. Floating-point addition is not associative: mathematically equal formulas can give different results, and compilers do not reorder them unless allowed (-ffast-math).
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Types and operators 9
- Control flow 9
- Functions 9
- Pointers 9
- Arrays and strings 9
- Memory management 9
- Structs and unions 9
- Preprocessor 9
- Standard library and I/O 9
- Undefined behavior 9
- Numerics in C 10
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по COBOL100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
