箭头操作符与点操作 [英] Arrow Operator vs. Dot Operator

查看:123
本文介绍了箭头操作符与点操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,将c的箭头操作符( - >)是不必要的。点运算符(。)应该足够了。看看下面的code:

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;

我们看到,箭头运营商必须使用间接引用吧。不过,我想preFER写

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

val = bar.member;

有没有歧义,以我是否试图从结构还是从指针到结构拉成员。但它很容易使用错误的操作者,重构code时尤其如此。 (例如,也许我做的一些foo的复杂的操作,所以移动code到一个新的功能,并传递一个指针富)。我不认为我需要关心是否富是一个指针与否;编译器可以不用担心的细节。

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.

所以问题:?不会是简单的消除 - >从C语言

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

推荐答案

在'箭头'运算符语法糖。 酒吧,>成员相同(*栏)。成员。这种差异的一个原因是可维护性。用箭头操作者从点运算不同,变得更容易跟踪哪些变量是指针和哪些不是。这可能是可能的,总是用键,让编译器尝试做正确的事情,但我怀疑这会使得语言更简单。信任编译器间preT你的意味着的,而不是你的字面上写的的通常结果糟糕。

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.

这篇关于箭头操作符与点操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆