ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int *slot(int i) { static int box[3]; return &box[i % 3]; }
int main(void) {
    *slot(0) = 5;
    *slot(4) = 7;
    int *p = slot(3);
    *p += *slot(1);
    p[2]--;
    printf("%d %d %d", *slot(0), *slot(1), *slot(2));
}
  1. A. 5 7 0
  2. B. 12 7 0
  3. C. 12 7 -1
  4. D. 5 12 -1

Correct answer: C. 12 7 -1

box has static storage: it is zero-initialised, exists for the whole program and every call returns a pointer into the same array, so returning its address is safe (unlike an automatic local). slot(4) is box[1] = 7 and slot(3) is box[0], so *p += 7 makes box[0] = 12; p[2] is box[2], decremented from 0 to −1. '5 7 0' treats each call as getting a fresh array.

More C Programming questions

Exams that ask this topic