ProgrammingModerateTCS NQT · Infosys

What is printed?

What is printed?
const char *s = "banana", *p = s;
int c = 0;
while ((p = strchr(p, 'a')) != NULL) { c++; p++; }
printf("%d", c);
  1. A. 3
  2. B. Nothing: it loops forever
  3. C. 2
  4. D. 6

Correct answer: A. 3

strchr returns a pointer to the next 'a', and p++ steps past it so the next search starts after it. Three a's give 3. Without the p++, strchr would keep finding the same 'a' forever.

More C Programming questions

Exams that ask this topic