ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
int arr[10];
for (int i = 0; i <= 10; i++) {
    arr[i] = i;
}
printf("done");
  1. A. It prints done; the loop just fills indices 0 through 10 inclusive
  2. B. Undefined behaviour: the loop condition i <= 10 allows i to reach 10, one past the last valid index (9) of a 10-element array
  3. C. Compile-time error: the loop bound does not match the array size
  4. D. It prints done, but only indices 0..9 are actually written since C ignores the extra iteration

Correct answer: B. Undefined behaviour: the loop condition i <= 10 allows i to reach 10, one past the last valid index (9) of a 10-element array

arr has valid indices 0..9; using <= instead of < in the loop condition is a classic off-by-one bug that lets i reach 10, causing arr[10] = 10; to write one element past the end of the array — an out-of-bounds write, which is undefined behaviour (it may silently corrupt adjacent stack memory rather than crashing, which is part of why this bug is so dangerous).

More C Programming questions

Exams that ask this topic