3

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

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 Answers2

4

List of operators that I can think of:

  1. The assignment operator - ptr = some other pointer
  2. The dereference operator - *ptr.
  3. The array operator - ptr[N].
  4. The member access operator ptr-> if T is a struct/class.
  5. The pre and post increment operators - ++ptr and ptr++.
  6. The pre and post decrement operators - --ptr and ptr--.
  7. The increment and assign operator - ptr += N.
  8. The decrement and assign operator - ptr -= N.
  9. The unary + operator: +ptr. Note that this is not valid in C99. It is valid only in C++.
  10. The binary + operator - ptr + N.
  11. The binary - operator - ptr - N and ptr1 - ptr2.
  12. Is equal to: ptr == some other pointer.
  13. Is not equal to: ptr != some other pointer.
  14. The unary not operator: !ptr.
  15. Less than operator : ptr < some other pointer.
  16. Less than or equal to operator: ptr <= some other pointer.
  17. Greater than operator : ptr > some other pointer.
  18. Greater than or equal to operator: ptr >= some other pointer.
  19. 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
  • @PaulEvans, interesting. I get an error using gcc 4.9.3 on cygwin. – R Sahu Oct 23 '15 at 19:37
  • 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