Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow Operator vs. Dot Operator [closed]

It seems to me that C's arrow operator (->) is unnecessary. The dot operator (.) should be sufficient. Take the following code:

typedef struct {     int member; } my_type;  my_type   foo; my_type * bar; int       val;  val = foo.member; val = bar->member; 

We see that the arrow operator must be used to dereference bar. However, I would prefer to write

val = bar.member; 

There is no ambiguity as to whether I am trying to pull 'member' from a structure or from a pointer to the structure. But it is easy to use the wrong operator, especially when refactoring code. (For example, maybe I am doing some complex operations on foo, so I move the code into a new function and pass a pointer to foo). I don't think I need to care whether foo is a pointer or not; the compiler can worry about the details.

So the question: wouldn't it be simpler to eliminate -> from the C language?

like image 424
remline Avatar asked Apr 05 '12 21:04

remline


People also ask

What does the -> mean in C?

The dot ( . ) operator is used to access a member of a struct, while the arrow operator ( -> ) in C is used to access a member of a struct which is referenced by the pointer in question.

What is arrow operator in C language?

In C, this operator enables the programmer to access the data elements of a Structure or a Union. This operator (->) is built using a minus(-) operator and a greater than(>) relational operator. Moreover, it helps us access the members of the struct or union that a pointer variable refers to.

What is difference between and -> in C++?

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow. :: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it.

Why do we use dot operators in C++?

(dot) operator is used to access class, structure, or union members. The member is specified by a postfix expression, followed by a . (dot) operator, followed by a possibly qualified identifier or a pseudo-destructor name.


1 Answers

The 'arrow' operator is syntactic sugar. bar->member is the same as (*bar).member. One reason for the difference is maintainability. With the arrow operator distinct from the dot operator, it becomes much easier to keep track of which variables are pointers and which are not. It might be possible to always use . and have the compiler try to do the right thing, but I doubt that would make the language simpler. Trusting the compiler to interpret what you meant instead of what you literally wrote usually turns out badly.

like image 60
bta Avatar answered Sep 20 '22 22:09

bta