ProgrammingVery hardProduct company OA

What is printed?

What is printed?
const char *s = "";
int n = 0;
for (int i = 0; i < strlen(s) - 1; i++) {
    n++;
    if (n > 5) break;
}
printf("%d", n);
  1. A. 1
  2. B. 0
  3. C. Nothing: it loops forever
  4. D. 6

Correct answer: D. 6

strlen returns size_t, which is unsigned, so strlen("") − 1 wraps to SIZE_MAX, and i is converted to size_t for the comparison. 0 < SIZE_MAX is true, so only the break ends the loop, with n = 6. The intended '0' needs a signed comparison or i + 1 < strlen(s).

More C Programming questions

Exams that ask this topic