ProgrammingHardTCS NQT · Wipro

What is printed?

What is printed?
#include <stdio.h>
void inc(int *p, int n) {
    while (n--) (*p++)++;
}
int main(void) {
    int a[] = {1, 2, 3};
    inc(a, 2);
    printf("%d", a[0] + a[1] + a[2]);
}
  1. A. 6
  2. B. 8
  3. C. 9
  4. D. Undefined: p and *p are both modified in one expression

Correct answer: B. 8

(*p++)++ increments the int p points at, then advances p; these are two different objects, so it is well defined. With n = 2 the array becomes {2, 3, 3}, sum 8; 9 runs the loop three times, and 6 thinks only the pointer moves.

More C Programming questions

Exams that ask this topic