2

Consider this case:

int *ptr;
int offset;
ptr = <some_address>;
offset = 10;

Assume that offset is 32-bit variable. ptr has type int*, the target architecture is 64-bit (so ptr is 8-byte variable), offset has type int. What conversion will be performed when calculating value of expression*(ptr + offset)? Where can I read about it in the 2003 C++ standard?

Alexander_KH
  • 189
  • 12
  • The `offset` variable should be converted to [`std::ptrdiff_t`](http://en.cppreference.com/w/cpp/types/ptrdiff_t). – Some programmer dude May 07 '15 at 08:32
  • I'd guess the smaller integer variable gets promoted, and that's either `int` for `offset` or `size_t`/`std::ptrdiff_t` (as pointed out by Joachim Pileborg) for `ptr` – Binkan Salaryman May 07 '15 at 08:32
  • I thought about promotion, but found nothing about this particular case in the 2003 C++ standard. – Alexander_KH May 07 '15 at 08:35
  • 1
    Fwiw, the pointer *type* shouldn't matter (who cares if it points to an `__int64`, a `char`, or anything in between). There may be *alignment* issues, but that doesn't seem related to your question. That it is a pointer *at all* is certainly related. If you were trying to say "assume platform data pointers are 64bit, and platform `int` is 32bit, you should probably just say it (at least I think that's what you meant). – WhozCraig May 07 '15 at 08:45

1 Answers1

5

This is what the standard has to say about this [expr.add]/4:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object84, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i ≠ n-th elements of the array object, provided they exist.

In simpler words, this means that the address where ptr points to is incremented by offset * sizeof(*ptr) when you write ptr + offset.

user1978011
  • 3,419
  • 25
  • 38