1

Possible Duplicate:
Why does C have a distinction between -> and .?

Compilers are smart enough to know if the left side operand is a pointer or a reference. Why are there two different operators (. and ->) for member access?

Is it to make the indirection explicit? For legibility? Was there something about the available hardware when C was designed that made a strong case for those operations to be easily distinguished when reading source code?

I've read about it simply being a shorthand syntax for (*ptr).member, but is ptr.member ever valid when ptr is a pointer? Why can't ptr.member "just work" as ptr->member if ptr is a pointer?

2
  • Yes, exact duplicate. I should have searched more. Dec 18, 2012 at 2:03
  • 1
    a) "Why can't ptr.member "just work" as ptr->member if ptr is a pointer?" it could, in C, but doesn't for historical reasons. b) In C++ it would be an incompatible change due to operator overloading. c) Note that function pointers are automatically dereferenced ... p() is equivalent to (********p)() d) Use a more modern language like rust or D.
    – Jim Balter
    Dec 18, 2012 at 6:47

1 Answer 1

1

Not quite an answer, but one place this distinction is taken advantage of is with smart pointers and container iterators.

In both cases, the . operator is used to operate on the object itself, while the -> is used to operate on the object that is contained within.

Not the answer you're looking for? Browse other questions tagged or ask your own question.