Конвертер валютUSD 2,9921EUR 3,3424Моя статистикаПройдите любой тест
Все записи блога →
Последние Новости
  • Тур Хейердал — путешественник, переплывший океан на плоту
    Шесть мужчин, бальсовый плот и бескрайний Тихий океан. Тур Хейердал хотел проверить смелую идею: могли ли жители Южной Америки в древности добраться до островов Полинезии. Чтобы узнать это, он сам отправился в путь.Путь к успехуТур Хейердал родился 6 октября 1914 года в городе Ларвик в Норвегии. С детства он увлекался зоологией и дикой природой. В 1937–1938 годах Тур с женой прожил около года на острове Фату-Хива в Полинезии. Именно там, наблюдая за ветрами и течениями, он задумался о происхожде...
  • Христофор Колумб — мореплаватель, открывший Европе Америку
    Утром 12 октября 1492 года матрос с корабля «Пинта» крикнул, что видит берег. Через несколько часов три небольших судна подошли к острову, который местные жители называли Гуанахани. Экспедиция Христофора Колумба завершила первый переход через Атлантический океан, после которого мир перестал быть прежним.Путь к экспедицииКолумб родился около 1451 года в Генуе в семье ткача. Он рано ушёл в море, плавал по Средиземному и Атлантическому океанам, жил в Португалии. Он был уверен, что до Индии и Китая ...
  • Фрэнк Синатра — «Голос» века, певший по-своему
    Шляпа с лентой, небрежно накинутый плащ, бархатный баритон — Фрэнк Синатра умел превратить трёхминутную песню в маленький спектакль. Прозвище «Голос» закрепилось за ним ещё в 1940-х, и за десятилетия его мало кто смог оспорить.Путь к успехуСинатра родился в декабре 1915 года в Хобокене, штат Нью-Джерси, в семье итальянских эмигрантов. Музыкального образования он почти не получил, зато с юности пел на радио и в клубах. Первые успехи пришли в оркестрах Гарри Джеймса и Томми Дорси. В начале 194...
  • Михаил Булгаков — мастер, которого прочли после смерти
    Автор, которого при жизни почти не печатали, оказался одним из самых читаемых писателей столетия. История Михаила Афанасьевича Булгакова — это история терпения, упорства и веры в свою книгу.Путь к успехуБулгаков родился в 1891 году в Киеве, в семье преподавателя духовной академии. В 1916 году он окончил медицинский факультет Киевского университета и сразу начал работать врачом, в том числе в земской больнице в селе Никольском Смоленской губернии. Эти годы позже отразились в «Записках юного врача...
  • Дмитрий Менделеев — химик, составивший карту всех элементов
    Дмитрий Иванович Менделеев родился 8 февраля 1834 года (27 января по старому стилю) в Тобольске, в большой семье директора гимназии. Рос он в трудное время, но мать, по семейным преданиям, сделала всё, чтобы младший сын получил образование. Так будущий учёный оказался в Петербурге.Путь к успехуОкончив Главный педагогический институт, Менделеев стажировался в Европе, а в 1860-х годах стал профессором Петербургского университета. Читая курс неорганической химии, он не нашёл подходящего учебника и ...
  • Роальд Амундсен — покоритель полюсов и северо-западного прохода
    Полярные льды веками хранили свои тайны. Роальд Амундсен разгадал сразу несколько из них. Он не искал лёгкой славы: каждый его поход был итогом долгой учёбы у местных народов и внимательного расчёта.Путь к успехуАмундсен родился 16 июля 1872 года недалеко от города Борге в Норвегии. Он собирался стать врачом, но, прочитав о полярных экспедициях, выбрал другую жизнь. В 1897–1899 годах он участвовал в бельгийской экспедиции на судне «Бельжика», которая стала первой, перезимовавшей в Антарктике. Та...
  • Франциск Скорина — первопечатник Беларуси и Восточной Европы
    В 1517 году в Праге вышла небольшая книга, которую можно держать в одной руке. Это была Псалтирь, а на её страницах стояло имя издателя: «Франциск Скорина из Полоцка, в лекарских науках доктор». Так началась история восточнославянского книгопечатания.Путь к книгеТочная дата рождения Скорины неизвестна, обычно называют около 1490 года. Он родился в Полоцке в семье купца. В 1504 году его имя записано среди студентов Краковского университета. В 1512 году в итальянской Падуе он получил степень докто...
  • Марк Шагал — художник, чьи герои парят над городом
    На картинах Марка Шагала люди летают над крышами, скрипач сидит на домике, а синяя корова смотрит на зрителя человеческими глазами. Это не просто фантазия: художник всю жизнь рисовал родной Витебск, каким его хранила память, — с поэтической логикой сна.Путь к успехуМарк Шагал (при рождении Мовша Шагал) родился в 1887 году в семье бедного еврейского рабочего недалеко от Витебска и вырос в самом Витебске. Он учился у местного художника Юделя Пэна, затем уехал в Санкт-Петербург. В 191...
  • Янка Купала — народный поэт Беларуси
    Когда в начале XX века молодой поэт из деревни под Минском подписал свои стихи псевдонимом «Янка Купала», он, возможно, и не думал, что станет голосом целого народа. Но именно так и произошло.Путь к успехуИван Доминикович Луцевич родился в 1882 году в фольварке Вязынка близ Молодечно. Семья была небогатой: родители арендовали землю. Учился он в народном училище, потом работал домашним учителем, писарем, помощником провизора, много читал и рано начал писать стихи. Первое стихотворение «Мужик» нап...
  • Луи Пастер — учёный, победивший невидимых врагов
    Луи Пастер родился 27 декабря 1822 года в городке Доль на востоке Франции, в семье кожевника. Он был прилежным, но не блестящим учеником и интересовался живописью. Однако судьбу решила химия: она повела его от кристаллов к микробам и спасению жизней.Путь к успехуПервое крупное открытие Пастер сделал в 1848 году, изучая кристаллы солей винной кислоты. Он заметил, что они бывают двух зеркально отражённых форм, и тем самым заложил основы стереохимии. Позже он занялся брожением и показал, что за нег...
МатематикаМоя статистика

Тест по языку C

100 вопросов в 11 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.

Типы и операторы, функции, указатели, массивы и строки, malloc и free, структуры, препроцессор, printf и stdio, неопределённое поведение и вычисления с плавающей точкой. Вопросы на английском.

Все вопросы теста 100

Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».

Types and operators9
1Лёгкий
What does this code print?
int a = 7, b = 2;
double r = a / b;
printf("%.1f\n", r);
  1. 3.0
  2. 3.5
  3. 4.0
  4. It does not compile: an int expression cannot be assigned to a double
2Средний
What does this code print (C99 or later)?
printf("%d %d\n", -7 / 2, -7 % 2);
  1. -3 -1
  2. -4 1
  3. -3 1
  4. -4 -1
3Лёгкий
What is sizeof(char) in C?
  1. 8, because a char has 8 bits
  2. Always 1, by definition
  3. 2 on systems that use Unicode
  4. It depends on the compiler, just like sizeof(int)
4Сложный
What does this code print?
int i = -1;
unsigned int u = 1;
if (i < u)
    puts("less");
else
    puts("not less");
  1. not less
  2. less
  3. Nothing: comparing signed and unsigned values is a compile error
  4. It is undefined behaviour, so the output is unpredictable
5Сложный
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;
}
  1. It returns 4294836225, because the result is returned as unsigned int
  2. Undefined behaviour: x is promoted to signed int and 65535 * 65535 overflows int
  3. It returns 1, because unsigned short arithmetic wraps modulo 65536
  4. It does not compile without an explicit cast to unsigned int
6Лёгкий
What does this code print?
int i = 5;
int j = i++;
int k = ++i;
printf("%d %d %d\n", i, j, k);
  1. 7 6 7
  2. 6 5 6
  3. 7 5 7
  4. 7 5 6
7Средний
Which statement about the plain type char is true?
  1. Whether char is signed or unsigned is implementation-defined; char, signed char and unsigned char are three distinct types
  2. char is always signed, exactly like signed char
  3. char is always unsigned, because character codes are never negative
  4. char is signed on 64-bit systems and unsigned on 32-bit systems
8Средний
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);
  1. 44 44
  2. 300 44
  3. 300 300
  4. Nothing definite: 200 + 100 overflows unsigned char, which is undefined behaviour
9Сложный
With 32-bit int, what does this code print?
printf("%zu %zu\n", sizeof('a'), sizeof(char));
  1. 1 1
  2. 4 1
  3. 2 1
  4. 1 4
Control flow9
10Лёгкий
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");
  1. two
  2. two three
  3. two three other
  4. one two three
11Лёгкий
What does this loop print?
for (int i = 0; i < 10; i += 3)
    printf("%d ", i);
  1. 0 3 6
  2. 0 3 6 9
  3. 3 6 9
  4. 0 3 6 9 12
12Средний
What does this code print?
int x = 5;
if (x = 0)
    puts("zero");
else
    puts("nonzero");
printf("%d\n", x);
  1. nonzero, then 5
  2. zero, then 0
  3. zero, then 5
  4. nonzero, then 0
13Сложный
What does this code print?
int a = 0, b = 1;
if (a)
    if (b)
        puts("A");
else
    puts("B");
puts("C");
  1. Only C
  2. B, then C
  3. A, then C
  4. Nothing: the else is ambiguous, so it does not compile
14Средний
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);
  1. 3
  2. 1
  3. 9
  4. 0
15Лёгкий
What does this code print?
int n = 10;
do {
    printf("%d\n", n);
    n++;
} while (n < 5);
  1. Nothing
  2. 10
  3. 10, then 11
  4. It counts up from 10 forever
16Средний
What happens when this loop runs?
int i = 0;
while (i < 5) {
    if (i == 2)
        continue;
    printf("%d ", i);
    i++;
}
  1. It prints 0 1 3 4
  2. It never terminates: after 0 and 1 are printed, i stays 2
  3. It prints 0 1 2 3 4
  4. It prints 0 1 and stops
17Сложный
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];
  1. It sums x[4] down to x[0] and stops
  2. It sums x[4] down to x[1] and stops; x[0] is skipped
  3. It does not compile: an unsigned variable cannot be decremented
  4. i >= 0 is always true for unsigned, so after 0 i wraps to UINT_MAX and x is read far out of bounds
18Лёгкий
What does this code print?
int a = 0, b = 0;
if (a++ && b++)
    puts("both");
printf("%d %d\n", a, b);
  1. 1 1
  2. 1 0
  3. 0 0
  4. both, then 1 1
Functions9
19Лёгкий
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. 1 2
  2. 2 1
  3. 2 2
  4. It does not compile: a and b must be pointers
20Средний
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. 1
  2. 0
  3. 2
  4. 3
21Лёгкий
What does printf("%d\n", fact(5)) print?
int fact(int n)
{
    return n <= 1 ? 1 : n * fact(n - 1);
}
  1. 24
  2. 5
  3. 120
  4. 720
22Средний
In C99/C11 (unlike C++), what does the declaration int f(); mean?
  1. f takes no arguments, exactly like int f(void)
  2. f returns int and its parameters are unspecified — it is not a prototype, so calls are not checked
  3. f takes any number of int arguments, like int f(int, ...)
  4. It is a syntax error: a parameter list cannot be empty
23Сложный
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;
}
  1. 5 5
  2. 8 15
  3. 5 15
  4. 5 9
24Лёгкий
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;
}
  1. 5 6
  2. 0 6
  3. 0 0
  4. It does not compile: arrays cannot be passed to functions
25Средний
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;
}
  1. norm2's local variables keep their values between calls
  2. norm2 is evaluated at compile time
  3. norm2 cannot call other functions or itself
  4. norm2 has internal linkage: it can only be called from the same source file
26Средний
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;
}
  1. 18
  2. 12
  3. It does not compile: functions cannot be stored in an array
  4. 15
27Сложный
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;
}
  1. va_arg(ap, double)
  2. va_arg(ap, float)
  3. (float)va_arg(ap, int)
  4. *(float *)ap
Pointers9
28Лёгкий
What does this code print?
int x = 10;
int *p = &x;
*p = 20;
printf("%d\n", x);
  1. 20
  2. 10
  3. The address of x
  4. It does not compile: *p cannot be assigned
29Лёгкий
What does this code print?
int a[] = {10, 20, 30, 40};
int *p = a;
p += 2;
printf("%d %d\n", *p, *(p - 1));
  1. 30 20
  2. 20 10
  3. 30 29
  4. Garbage: p += 2 moves only 2 bytes into a[0]
30Средний
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. 1 2 2
  2. 2 2 1
  3. 2 3 1
  4. 1 2 1
31Средний
Which statement, added after these declarations, does NOT compile?
int x = 1, y = 2;
const int *p = &x;
int *const q = &x;
  1. p = &y;
  2. *q = 5;
  3. *p = 5;
  4. x = 5;
32Сложный
What does this code print?
int a[5] = {1, 2, 3, 4, 5};
int *p = (int *)(&a + 1);
printf("%d\n", *(p - 1));
  1. 2
  2. 5
  3. 1
  4. It crashes: &a + 1 points outside the array
33Лёгкий
What does this code print?
int x = 3;
int *p = &x;
int **pp = &p;
**pp = 7;
printf("%d\n", x);
  1. 3
  2. 7
  3. The address of x
  4. It does not compile: a pointer cannot point to another pointer
34Лёгкий
What are the types of p and q after this declaration?
int* p, q;
  1. Both p and q are pointers to int
  2. Both are plain ints; the * is ignored
  3. p is a pointer to int, q is a plain int
  4. It does not compile: the * must be written next to the variable name
35Средний
What does this code print?
double d[10];
double *a = &d[2];
double *b = &d[7];
printf("%td\n", b - a);
  1. 40
  2. -5
  3. 5
  4. It does not compile: pointers cannot be subtracted
36Сложный
What does this code print?
int a[] = {1, 2, 3};
int *p = a + 1;
printf("%d %d\n", p[-1], 2[a]);
  1. 2 3
  2. Nothing definite: a negative index is undefined behaviour
  3. It does not compile: 2[a] is not valid syntax
  4. 1 3
Arrays and strings9
37Лёгкий
What does this code print?
char s[] = "hello";
printf("%zu %zu\n", sizeof s, strlen(s));
  1. 6 5
  2. 5 5
  3. 5 6
  4. 8 5
38Средний
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;
}
  1. 10, then 10
  2. 10, then 1
  3. 10, then 2
  4. 40, then 8
39Средний
What does this code print?
char a[] = "abc";
char b[] = "abc";
printf("%d %d\n", a == b, strcmp(a, b) == 0);
  1. 1 1
  2. 1 0
  3. 0 0
  4. 0 1
40Сложный
What does buf contain after this call?
char buf[4];
strncpy(buf, "hello", sizeof buf);
  1. "hel" followed by '\0', because strncpy always terminates the copy
  2. "hello", because strncpy enlarges the buffer as needed
  3. 'h', 'e', 'l', 'l' with no terminating '\0' — it is not a valid string
  4. Nothing: strncpy refuses to copy when the source is too long
41Лёгкий
What does this code print?
int a[5] = {1, 2};
printf("%d %d %d\n", a[1], a[2], a[4]);
  1. 2 followed by two unpredictable values
  2. 1 0 0
  3. 2 0 0
  4. It does not compile: the initializer has too few values
42Лёгкий
What does this code print?
printf("%zu %zu\n", strlen("abc\0def"), sizeof "abc\0def");
  1. 7 8
  2. 3 8
  3. 3 4
  4. 7 7
43Средний
What happens here?
char *s = "hello";
s[0] = 'H';
puts(s);
  1. It prints Hello
  2. It prints hello, because the assignment changes a copy
  3. It does not compile: s[0] cannot be assigned through a char *
  4. Undefined behaviour: string literals must not be modified (often a crash, as they live in read-only memory)
44Средний
What is wrong with this code?
char name[8];
strcpy(name, "Christine");
  1. Buffer overflow (undefined behaviour): "Christine" needs 10 bytes including the terminating '\0'
  2. Nothing serious: strcpy truncates the copy to "Christi" plus '\0'
  3. name holds "Christin" without '\0', otherwise it is safe
  4. It does not compile: the string is longer than the array
45Сложный
Is this declaration valid C, and what does s contain?
char s[5] = "hello";
  1. Valid in C: s holds the 5 characters h e l l o with no terminating '\0', so it is not a string
  2. Valid: the compiler enlarges s to 6 elements to fit the '\0'
  3. Invalid: the initializer is too long, so it does not compile
  4. Valid: s holds "hell" followed by '\0'
Memory management9
46Лёгкий
Which standard function allocates memory and sets all of its bytes to zero?
  1. malloc
  2. realloc
  3. calloc
  4. alloca
47Лёгкий
What is wrong with this code?
double *p = malloc(100 * sizeof *p);
p = malloc(200 * sizeof *p);
free(p);
  1. The first block is leaked: its only pointer was overwritten before it was freed
  2. Nothing: the second malloc automatically frees the first block
  3. Nothing: free(p) releases both blocks
  4. sizeof *p dereferences an uninitialized pointer
48Средний
What is the problem with the realloc line?
double *v = malloc(n * sizeof *v);
/* ... fill v ... */
v = realloc(v, 2 * n * sizeof *v);
  1. realloc frees the old block even when it fails, so v dangles
  2. realloc does not preserve the old contents, so the data is lost
  3. realloc can only shrink a block, never grow it
  4. If realloc fails it returns NULL, v is overwritten and the original block is leaked
49Средний
What happens here?
int *p = malloc(sizeof *p);
*p = 42;
free(p);
if (p != NULL)
    printf("%d\n", *p);
  1. It prints 42, because free only marks the memory as reusable
  2. It prints nothing, because free sets p to NULL
  3. It prints 0, because free clears the memory
  4. Undefined behaviour: free does not set p to NULL, so *p reads freed memory
50Сложный
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;
}
  1. It sets a[2] = 5, because realloc always grows a block in place
  2. It sets a[2] = 5, because realloc updates every pointer into the block
  3. It is fine as long as the new size is larger than the old one
  4. Undefined behaviour: the block may have moved, and mid still points into the old one
51Лёгкий
What does malloc return when it cannot allocate the requested memory?
  1. A pointer to a zero-sized block
  2. Nothing: it terminates the program with an "out of memory" message
  3. A null pointer
  4. Nothing: it throws an exception that the caller can catch
52Средний
p was set by a successful int *p = malloc(10 * sizeof *p); and not yet freed. Which call is guaranteed to be safe?
  1. free(p + 1);
  2. free(p); free(p);
  3. free(NULL);
  4. int a[10]; free(a);
53Средний
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;
}
  1. Nothing: arrays are always allocated on the heap
  2. Nothing: the array is copied to the caller because it is returned
  3. Nothing, as long as the caller uses the result before calling another function
  4. v is a local array that ceases to exist when the function returns, so the caller gets a dangling pointer
54Сложный
What is wrong with this function?
char *dup(const char *t)
{
    char *s = malloc(strlen(t));
    if (s != NULL)
        strcpy(s, t);
    return s;
}
  1. Nothing: strlen counts the terminating '\0' too
  2. The result of malloc must be cast to (char *) in C
  3. The buffer is one byte too small: strcpy also writes the terminating '\0', a heap overflow
  4. strcpy needs the length as a third argument
Structs and unions9
55Лёгкий
Given these declarations, which expression is equivalent to p->x?
struct point { int x, y; };
struct point a = {1, 2};
struct point *p = &a;
  1. *p.x
  2. p.x
  3. (*p).x
  4. &p.x
56Средний
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));
  1. 6
  2. 9
  3. 12
  4. 8
57Средний
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));
  1. 15
  2. 16
  3. 8
  4. 3
58Сложный
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));
  1. 10 10
  2. 16 16
  3. 24 16
  4. 24 24
59Лёгкий
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);
  1. 5 0 0
  2. 0 0 5
  3. Two unpredictable values, then 5
  4. It does not compile: designated initializers exist only in C++
60Средний
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]);
  1. 9 9
  2. 1 9
  3. 1 1
  4. It does not compile: arrays cannot be copied
61Лёгкий
What happens with this code?
struct point { int x, y; };
struct point a = {1, 2}, b = {1, 2};
if (a == b)
    puts("equal");
  1. It does not compile: == is not defined for structures
  2. It prints equal
  3. It prints nothing, because == compares the addresses of a and b
  4. It compares the structs byte by byte, including padding
62Средний
Why is the member next declared as struct node * instead of Node *?
typedef struct node {
    double value;
    struct node *next;
} Node;
  1. Node * would make next a copy of the whole node rather than a pointer
  2. Members of a struct can never use typedef names
  3. struct node * makes next point to the node itself automatically
  4. The typedef name Node does not exist until the end of the declaration, but the tag struct node is already in scope
63Сложный
How do you allocate a struct series whose data member can hold n values?
struct series {
    size_t n;
    double data[];
};
  1. malloc(sizeof(struct series) + n * sizeof(double))
  2. malloc(n * sizeof(struct series))
  3. malloc(n * sizeof(double)), because data is the only array
  4. struct series s = { n }; — data is sized automatically
Preprocessor9
64Средний
What does this code print?
#define SQUARE(x) x * x

printf("%d\n", SQUARE(1 + 2));
  1. 9
  2. 3
  3. 5
  4. It does not compile: a macro argument cannot contain an operator
65Лёгкий
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
  1. They stop the header from being included in more than one .c file of the program
  2. A second #include of the header in the same source file expands to nothing, so nothing is defined twice
  3. They make the compiler compile the header only once and cache the result
  4. They declare VECTOR_H as a global variable that other files can test
66Средний
What is the conventional difference between #include <stdio.h> and #include "matrix.h"?
  1. <...> works only for the C standard headers; your own headers can never be included with it
  2. The "..." form first looks for the file relative to the including source file, then falls back to the paths searched by <...>
  3. "..." includes the file at link time, <...> at compile time
  4. There is none: both forms search exactly the same directories in the same order
67Сложный
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);
  1. 5 6
  2. 6 6
  3. Undefined behaviour: i is modified twice without a sequence point
  4. 6 7
68Лёгкий
When is a macro such as #define N 100 replaced in the code?
  1. At run time, when the line is executed
  2. At link time, when the object files are combined
  3. During preprocessing, as token substitution, before the compiler proper sees the code
  4. During compilation, after type checking, like a const variable
69Лёгкий
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;
}
  1. checking input, then done
  2. Nothing
  3. done
  4. It does not compile: DEBUG is not defined
70Средний
Why does this code fail to compile?
#define PI 3.14159;

double area(double r)
{
    return PI * r * r;
}
  1. PI is already defined in math.h, so redefining it is an error
  2. Macros cannot be used inside functions
  3. An object-like macro name must be followed by parentheses
  4. The semicolon is part of the macro, so the line becomes return 3.14159; * r * r; and * r * r; is invalid
71Сложный
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));
  1. 42 42
  2. N N
  3. N 42
  4. 42 N
72Сложный
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. 1 2
  2. 2 1
  3. It does not compile: a macro cannot expand to several statements
  4. 2 0
Standard library and I/O9
73Лёгкий
Which call correctly reads a number into the variable double d;?
  1. scanf("%f", &d);
  2. scanf("%lf", &d);
  3. scanf("%lf", d);
  4. scanf("%d", &d);
74Средний
On Linux, gcc solve.c -o solve fails with "undefined reference to 'sqrt'", although solve.c contains #include <math.h>. Why?
  1. The header only declares sqrt; the math library itself must be linked with -lm, placed after the source file
  2. math.h must be included before stdio.h
  3. sqrt exists only when compiling with -std=c99
  4. The argument of sqrt must be cast to double
75Средний
What does this code print?
printf("[%8.3f]\n", 3.14159);
  1. [ 3.142]
  2. [3.142 ]
  3. [ 3.14]
  4. [3.14159 ]
76Сложный
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);
  1. 6
  2. 3
  3. Nothing: it loops forever
  4. 9
77Лёгкий
What does this code print?
printf("%d%%\n", 50);
  1. 50%%
  2. 50
  3. %d%
  4. 50%
78Лёгкий
What happens to an existing file data.txt when it is opened with fopen("data.txt", "w")?
  1. Its contents are erased (truncated to length zero)
  2. New output is appended at the end of the old contents
  3. fopen fails because the file already exists
  4. The old contents are kept and overwritten byte by byte from the start
79Средний
What does this code print?
int n = printf("x=%d\n", 42);
printf("%d\n", n);
  1. x=42, then 4
  2. x=42, then 5
  3. x=42, then 1
  4. x=42, then 0
80Средний
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));
  1. 4
  2. 3
  3. 16
  4. 5
81Сложный
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);
  1. "hello\n"
  2. "5\nhello\n"
  3. Only "\n" — the newline left in the input by scanf
  4. An empty string "", because scanf consumed the whole line
Undefined behavior9
82Средний
What does this code print?
int i = 1;
i = i++ + 1;
printf("%d\n", i);
  1. 2
  2. 3
  3. 1
  4. Nothing definite: the behaviour is undefined
83Лёгкий
What does this code print?
int a[3] = {1, 2, 3};
printf("%d\n", a[3]);
  1. 0, because elements past the end read as zero
  2. 3, because a[3] is the last element
  3. The program stops with an "index out of range" error
  4. Nothing definite: a[3] is past the end of the array, so the behaviour is undefined
84Сложный
Why may gcc -O2 compile this function to simply "return 0"?
int will_overflow(int x)
{
    return x + 1 < x;
}
  1. Signed overflow is undefined, so the compiler may assume x + 1 never wraps, which makes x + 1 < x always false
  2. Because int becomes 64 bits wide at -O2, so x + 1 cannot wrap
  3. Because the comparison is removed only when x is a compile-time constant
  4. It may not: the standard requires x + 1 to wrap to INT_MIN, so the function must return 1 for INT_MAX
85Лёгкий
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);
  1. 10, because local variables start at zero
  2. 10, because double variables are always initialized to 0.0
  3. It does not compile: sum must be initialized
  4. Nothing definite: sum is never initialized, so the result is unpredictable
86Средний
What does this code print?
int i = 1;
printf("%d %d\n", i++, i++);
  1. 1 2
  2. Nothing definite: i is modified twice in unsequenced arguments, so the behaviour is undefined
  3. 2 1
  4. 1 1
87Лёгкий
What happens here?
int *p = NULL;
*p = 5;
  1. Undefined behaviour; on most systems the program crashes (e.g. segmentation fault)
  2. It stores 5 at address 0, which is reserved for such writes
  3. Nothing: writes through a null pointer are ignored
  4. It does not compile: NULL cannot be dereferenced
88Сложный
Assume 32-bit int. Which of these expressions has well-defined behaviour?
  1. UINT_MAX + 1u, which is 0
  2. INT_MAX + 1, which is INT_MIN
  3. -INT_MIN, which is INT_MIN
  4. 1 << 31, which is INT_MIN
89Сложный
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;
  1. bits = *(unsigned int *)&f;
  2. memcpy(&bits, &f, sizeof bits);
  3. bits = (unsigned int)f;
  4. bits = *(unsigned int *)(void *)&f;
90Средний
What does this code print?
const int limit = 10;
int *p = (int *)&limit;
*p = 20;
printf("%d\n", limit);
  1. 20
  2. 10, because writes through p are ignored
  3. Nothing definite: modifying an object defined const is undefined behaviour
  4. It does not compile: a cast cannot remove const
Numerics in C10
91Лёгкий
What does this code print?
printf("%d\n", 0.1 + 0.2 == 0.3);
  1. 1
  2. 0
  3. It does not compile: == cannot compare doubles
  4. Nothing definite: comparing doubles with == is undefined behaviour
92Средний
What does this code print?
float f = 0.1f;
double d = 0.1;
printf("%d\n", f == d);
  1. 1
  2. 0
  3. It does not compile: a float cannot be compared with a double
  4. 1 on 32-bit systems and 0 on 64-bit systems
93Средний
Which test is the most robust way to check that two computed doubles a and b are equal "up to rounding errors"?
  1. a == b
  2. fabs(a - b) <= 1e-9 * fmax(fabs(a), fabs(b))
  3. a - b < 1e-9
  4. (int)a == (int)b
94Сложный
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);
  1. 16777217
  2. 16777216
  3. 16777218
  4. Nothing definite: the value does not fit in a float, so the behaviour is undefined
95Лёгкий
For general scientific computing in C, why is double usually preferred over float?
  1. double carries about 15–16 significant decimal digits versus about 7 for float, so rounding errors build up far more slowly
  2. double is an integer type with a larger range
  3. math.h does not support float values
  4. double represents decimal fractions such as 0.1 exactly
96Средний
What does this code print?
double x = NAN;
printf("%d %d %d\n", x == x, x != x, isnan(x) != 0);
  1. 1 0 1
  2. 1 0 0
  3. 0 1 1
  4. 0 0 1
97Лёгкий
What does this code print (#include <math.h>)?
printf("%d %.1f %.1f\n", (int)-2.7, floor(-2.7), round(-2.7));
  1. -2 -3.0 -3.0
  2. -3 -3.0 -3.0
  3. -2 -2.0 -3.0
  4. -3 -2.0 -2.0
98Сложный
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);
  1. 16777216
  2. 20000000
  3. 19999999
  4. inf
99Средний
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);
  1. Nothing: the program crashes with a division-by-zero error
  2. 0.000000 0.000000
  3. nan nan
  4. inf -inf
100Средний
What does this code print?
double x = 1e-17;
printf("%g %g\n", (1.0 + x) - 1.0, x + (1.0 - 1.0));
  1. 1e-17 1e-17
  2. 0 0
  3. 1e-17 0
  4. 0 1e-17

Как проходить тест

  • Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
  • Отвечайте касанием или с клавиатуры: 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