ProgrammingModerateGATE CS · Infosys

Assume int is 4 bytes. What is printed?

Assume int is 4 bytes. What is printed?
#include <stdio.h>
int main(void) {
    int a[10];
    int *p = &a[7], *q = &a[2];
    printf("%ld %ld", (long)(p - q), (long)(q - p));
}
  1. A. 7 -2
  2. B. 5 -5
  3. C. 4 -4
  4. D. 6 -6

Correct answer: B. 5 -5

Pointer subtraction gives the number of ints between the two elements, here 7 - 2 = 5, and reversing the operands gives -5. Subtracting the other way round in the printed order is the trap.

More C Programming questions

Exams that ask this topic