AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardcarrayspointers

~90s

Subscripting written backwards

What does this C program print?

#include <stdio.h>

int main(void) {
    int a[5] = {10, 20, 30, 40, 50};
    printf("%d", 3[a] - a[1]);
    return 0;
}
Show the answer and the worked solution

Correct answer: B.

20

Worked solution

  1. The standard defines E1[E2] as *(E1 + E2), so 3[a] means *(3 + a), which is the same as *(a + 3), which is a[3].
  2. a[3] is 40 and a[1] is 20.
  3. The difference printed is 40 - 20 = 20.

Answer: 20.

The idea

Because subscripting is only sugar for pointer addition, the index and the array name can be written in either order. It is a curiosity rather than a style to adopt, but placement papers ask it often.

Shortcut. x[y] is defined as *(x + y), so 3[a] is a[3] = 40, and 40 − 20 = 20.

Common trap. 10 takes 3[a] as the third element, 30, counting from 1 instead of reading index 3; 30 − 20 = 10.

Subscripting written backwards — Aptitude Question

Subscripting written backwards: What does this C program print? Answer and worked solution on CodeKairo.

Question

What does this C program print?

#include <stdio.h>

int main(void) {
    int a[5] = {10, 20, 30, 40, 50};
    printf("%d", 3[a] - a[1]);
    return 0;
}

Options

  1. 10
  2. 20
  3. 30
  4. 40
Show the answer and the worked solution

Correct answer: B. 20

Worked solution

  1. The standard defines E1[E2] as *(E1 + E2), so 3[a] means *(3 + a), which is the same as *(a + 3), which is a[3].
  2. a[3] is 40 and a[1] is 20.
  3. The difference printed is 40 - 20 = 20.

Answer: 20.

The idea

Because subscripting is only sugar for pointer addition, the index and the array name can be written in either order. It is a curiosity rather than a style to adopt, but placement papers ask it often.

Shortcut. x[y] is defined as *(x + y), so 3[a] is a[3] = 40, and 40 − 20 = 20.

Common trap. 10 takes 3[a] as the third element, 30, counting from 1 instead of reading index 3; 30 − 20 = 10.

All Programming Fundamentals questions · placement mock tests