Possible Duplicates:
C++: ptr->hello(); /* VERSUS */ (*ptr).hello();
Why does C have a distinction between -> and . ?
I know the difference between the member operator (.) and the member by pointer operator (->).
Why did the C designers create a different operator for this access? Why can't the compiler figure it out on its own?
If you always used a . does any case exist where it is ambiguous whether you mean a member or a member by pointer?
edit: I'm not looking for the "(*a).b" syntax. I asking why didn't the designers allow you to use "a.b" instead of "a->b"?
Arrow operator to access the data member of a C Structure We have accessed the values of the data members using arrow operator(->).
operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers.
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable.
OR ( || ) - If EITHER or BOTH sides of the operator is true, the result will be true. AND ( && ) - If BOTH and ONLY BOTH sides of the operator are true, the result will be true. Otherwise, it will be false.
Would you really want the compiler to "figure it out on its own?" If it did, then the following would evaluate to the same thing (assuming p
is a pointer to a struct with a member x
):
(*p).x;
p.x
If the dereferencing of the pointer is implicit there, should it be implicit everywhere? Consider:
int* p;
int i = p; // should dereferencing be implicit here as well?
I think that would be far more confusing than having two separate operators.
It can also be helpful to have two operators to help keep track of how many layers of indirection you have. Granted, the ->
operator is not strictly necessary for this, since p->x
is equivalent to (*p).x
, but it does make code a bit clearer and easier to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With