Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer addition vs subtraction

Tags:

$5.7 -

"[..]For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type.

2 For subtraction, one of the following shall hold: — both operands have arithmetic or enumeration type; or — both operands are pointers to cv-qualified or cv-unqualified versions of the same completely defined object type; or — the left operand is a pointer to a completely defined object type and the right operand has integral or enumeration type.

int main(){
        int buf[10];
        int *p1 = &buf[0];
        int *p2 = 0;

        p1 + p2;       // Error

        p1 - p2;       // OK
}

So, my question is why 'pointer addition' is not supported in C++ but 'pointer subtraction' is?

like image 847
Chubsdad Avatar asked Aug 30 '10 10:08

Chubsdad


People also ask

Can we add or subtract pointers?

2. You can only add or subtract integers to pointers. When you add (or subtract) an integer (say n) to a pointer, you are not actually adding (or subtracting) n bytes to the pointer value. You are actually adding (or subtracting) n-times the size of the data type of the variable being pointed bytes.

What is pointer subtraction?

"When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them"

What is the rule for subtracting two pointers?

Two pointers can also be subtracted from each other if the following conditions are satisfied: Both pointers will point to elements of same array; or one past the last element of same array. The result of the subtraction must be representable in ptrdiff_t data type, which is defined in stddef.

Why pointer addition is not possible?

Pointers contain addresses. Adding two addresses makes no sense, because you have no idea what you would point to. Subtracting two addresses lets you compute the offset between these two addresses, which may be very useful in some situations.


1 Answers

The difference between two pointers means the number of elements of the type that would fit between the targets of the two pointers. The sum of two pointers means...er...nothing, which is why it isn't supported.

like image 124
Brian Hooper Avatar answered Sep 29 '22 01:09

Brian Hooper