Actual difference between operator point (.) and operator arrow (-) in C?

10

What is the real difference between the two operators.

I know that the (->) operator is used when the variable is a pointer, and that it is equal to (*ptr).membro . Well, if I declare a pointer of the type of a structure, I must use the arrow operator. If I declare an ordinary structure variable, I should use the dot operator. This I know.

What I really want to know is: what is the advantage of each other? When should I use one in view of the other? I have not yet seen the advantage of having two operators who apparently do the same thing.

    
asked by anonymous 19.02.2015 / 03:29

2 answers

11

Both are equivalent , there is no advantage in using one or the other, usually the copilator has something called "syntactic sugar", which is actually a facilitation to write the code, that is very visible in java where you can swap a + to a new StringBuilder () .

  

If there is an advantage, it would be in the organization / readability of the code!

(*(*(*a).b).c).d // não intuitivo

a->b->c->d // intuitivo

I looked for a reference to prove what I'm going to say now but I did not find, in some copiers, there is the pre-compilation substitution, the copier before performing the c-object replaces all occurrences of -> by (* p) .v, I know this is documented in the OCA books of java, it might be the same in c.

    
19.02.2015 / 05:10
10

The real difference is that the first is a reference to the member, you are simply saying that you should take the data from the member and the second is a dereference of the pointer contained in the member, saying that you should get the value pointed by the pointer on member. It is only syntactic sugar and the advantage is to write and read more easily. It is more obvious to see -> and to know what is happening than to interpret (*ptr).membro .

What does this do?

(*(*(*a).b).c).d

And this?

a->b->c->d

This is saying to get the value pointed out by d that is member of c that is member of b which in turn is member of a . The first one does the same thing but I will not even risk reading it aloud. Being explicit in intention is better.

In C ++ there is still the difference that the "arrow operator" can be overloaded.

C was meant to be an assembly portable and did not think much about the facilities for the programmer. If you think that normal in a program is working with final values and not with pointers, C is pretty annoying. By usability the normal would be to say that you want to catch the pointer by exception. But by C's philosophy this is not ideal. She has always sought to facilitate quick access and not usability. It was the 70s.

In fact there are discussions about how -> is unnecessary in language. It really is possible not to use it but it had to be defined at the beginning of the language. It is possible for the compiler to know how access should only be done with . but -> was not syntax sugar .

    
19.02.2015 / 12:17