Subscripting written backwards — Aptitude Question
Subscripting written backwards: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 90 seconds
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
- 10
- 20
- 30
- 40
Show the answer and the worked solution
Correct answer: B. 20
Worked solution
- 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].
- a[3] is 40 and a[1] is 20.
- 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