0

Consider the following c snippet:

int main(){
    int *a = (int *)60;
    int *b = (int *)40; 

    cout << a - b; 
    return 0;
}

The following code give output as 5. My understanding is int *a defines a pointer to memory address of 60, so going by this logic the output should be 20. On outputting the values of a and b, it gives the hexadecimal representation of 60 (0x3c) and 40 (0x28); still the program prints 5.

Can somebody please explain the reason behind this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sjsupersumit
  • 154
  • 2
  • 11
  • 1
    You only get 20 if `sizeof(char) == sizeof(int)`. – Jonathan Leffler Jun 07 '16 at 05:05
  • Got it. It gives how far the memory address are which is 5. as integer takes 4 byte of memory on 64 bit system. – sjsupersumit Jun 07 '16 at 05:06
  • 2
    *"as integer takes 4 byte of memory on 64 bit system"* - usually, and evidently so on your system if it's outputting 5, but that's not mandated by the C++ Standard (i.e. `int` could be larger). But the point is still that it's reporting the different in multiples of the size of the pointed-to type. – Tony Delroy Jun 07 '16 at 05:07

0 Answers0