1

I have the following question; If a is an int array with 10 Element I can define pointers

int*b=&a[3]; 
int*c=&[2];

I can then do arithmetic operations with these pointers like int d=a-c; which will return the number of int values in the array between b and c. So my question is if I am also allowed to do such pointer arithmetic operations for any variables which may not be in an array. For example:

int a=10; 
int b=20; 
int*c=&a; 
int* d=&b;

and then do int e=d-c; or int*e=c+1;

The reason I ask is that I have received conflicting information about whether this leads to undefined behaviour,

6

1 Answer 1

5

[expr.add] standard draft:

  1. 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 expression P points to element x[i] of an array object x with n elements,86 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0 ≤ i + j ≤ n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0 ≤ i − j ≤ n; otherwise, the behavior is undefined.

  2. When two pointers to elements of the same array object are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_- t in the header (21.2). If the expressions P and Q point to, respectively, elements x[i] and x[j] of the same array object x, the expression P - Q has the value i − j; otherwise, the behavior is undefined. [ Note: If the value i − j is not in the range of representable values of type std::ptrdiff_t, the behavior is undefined. — end note ]


86) An object that is not an array element is considered to belong to a single-element array for this purpose; see 8.3.1. A pointer past the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n] for this purpose; see 6.9.2.


c+1 is well defined, because it would be pointing one past the "single-element array" that the variable is treated as for the purpose of the quoted rule, and therefore satisfies 0 ≤ 0 + 1 ≤ 1. But it would not be well defined to indirect that pointer, since it past the end of that "array".

d-c has undefined behaviour.

Sign up to request clarification or add additional context in comments.

2 Comments

because it would be pointing one past the "single-element array" I don't think you can treat any variable as a single-element array. It is tempting but there doesn't seem to be any permit to do so in the standard.
@n.m. the standard rules can treat a variable as a single-element array and at least this one does. The programmer cannot (except to the extent that the standard allows).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.