Why addition of two pointers not supported in c or c++.
When I do,
int *ptr,*ptr1;
int sum = ptr + ptr1;
C or C++ throws an error. While it supports,
int diff = ptr - ptr1;
Why addition of two pointers not supported in c or c++.
When I do,
int *ptr,*ptr1;
int sum = ptr + ptr1;
C or C++ throws an error. While it supports,
int diff = ptr - ptr1;
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.
Edit: To address the common wish for finding the mid consider this (purely as an example):
#include <stdio.h>
int main (int argc, char **argv){
int arr[] = {0,1,2,3,4,5,6,7,8,9};
int *ptr_begin = arr;
int *ptr_end = &arr[9];
int *ptr_mid = ptr_begin + (ptr_end - ptr_begin)/2;
printf("%d\n", *ptr_mid);
}
I am quite sure that you can always come up with an offset-computation which lets do what you want to achieve with addition.
Adding two addresses actually can be useful, You may need to know the middle address between two adresses for example (a+b)/2 ( for the guy who want to think of pointers as house numbers, this would give him the number of the house in the middle between the two houses ), I think that adding two addresses should be allowed because you can do it anyway using casts :
int *ptr,*ptr1;
int sum = (int)ptr + (int)ptr1;
EDIT : I'm not saying that using adding addresses is obligatory in some cases, but it can be usefull when we know how to use it.
To put it plainly, difference between two pointers give the number of elements of the type that can be stored between the two pointers, but adding them doesn't quite give any meaningful functionality. If there's no meaningful functionality then doesn't it make sense that it is not supported.