For a given raw pointer type in C++, T* ptr
, what is the list of all the operators defined on it?
Asked
Active
Viewed 648 times
3

Vincent
- 57,703
- 61
- 205
- 388
-
Possible duplicate of [Pointer Arithmetic](http://stackoverflow.com/questions/394767/pointer-arithmetic) – cadaniluk Oct 23 '15 at 16:29
2 Answers
4
List of operators that I can think of:
- The assignment operator -
ptr = some other pointer
- The dereference operator -
*ptr
. - The array operator -
ptr[N]
. - The member access operator
ptr->
ifT
is a struct/class. - The pre and post increment operators -
++ptr
andptr++
. - The pre and post decrement operators -
--ptr
andptr--
. - The increment and assign operator -
ptr += N
. - The decrement and assign operator -
ptr -= N
. - The unary
+
operator:+ptr
. Note that this is not valid in C99. It is valid only in C++. - The binary
+
operator -ptr + N
. - The binary
-
operator -ptr - N
andptr1 - ptr2
. - Is equal to:
ptr == some other pointer
. - Is not equal to:
ptr != some other pointer
. - The unary not operator:
!ptr
. - Less than operator :
ptr < some other pointer
. - Less than or equal to operator:
ptr <= some other pointer
. - Greater than operator :
ptr > some other pointer
. - Greater than or equal to operator:
ptr >= some other pointer
. - The address of operator:
&ptr
.

Paul Evans
- 27,315
- 3
- 37
- 54

R Sahu
- 204,454
- 14
- 159
- 270
-
What about `+ptr` and `ptr += N` and `ptr -= N` and `ptr1 - ptr2`? Put in loads of *and*s to make it clearer. – Paul Evans Oct 23 '15 at 19:03
-
@PaulEvans, the unary + operator is not valid for pointers but the others you suggested are. I added them to my answer. – R Sahu Oct 23 '15 at 19:15
-
+1 Interesting, obviously `+ptr` does nothing but I suppose it makes sense not to allow it since `-ptr` wouldn't make any sense at all. Obviously most compilers ignore `+ptr` as a courtesy -- but is it? What if you meant `N+ptr` but lost through an accident of editing the `N`! – Paul Evans Oct 23 '15 at 19:22
-
My gcc 5.2.0 with `-Wall` doesn't on cygwin 2.2.1(0.289/5/3) for either `ptr2 = +ptr1;` or `*(+ptr)`. – Paul Evans Oct 23 '15 at 19:34
-
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/93207/discussion-between-paul-evans-and-r-sahu). – Paul Evans Oct 23 '15 at 19:40
0
Assuming
T* t;
dereference
(*t).foo
or
t->foo
pointer arithmetic
t = t + 10; t += 10; // will add 10*sizeof(T)
t = t - 10; t -= 10; // will subtract 10*sizeof(T)
--t;
++t;
t--;
t++;
access like an array: (usually frowned upon)
t[10]

GreatAndPowerfulOz
- 1,767
- 13
- 19