Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the rationale for difference between -> and . in c/c++? [duplicate]

Tags:

c++

c

standards

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"?

like image 806
Good Person Avatar asked May 29 '10 23:05

Good Person


People also ask

Why do we use -> in C?

Arrow operator to access the data member of a C Structure We have accessed the values of the data members using arrow operator(->).

What is the difference between operator and -> 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.

Whats the difference between & and * in C?

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.

What is the difference between && and || in C?

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.


1 Answers

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.

like image 178
James McNellis Avatar answered Oct 12 '22 02:10

James McNellis