箭头运算符与点运算符 [英] Arrow Operator vs. Dot Operator

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

问题描述

在我看来,C 的箭头运算符 (->) 是不必要的.点运算符 (.) 应该足够了.取以下代码:

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;

我们看到必须使用箭头运算符来取消引用 bar.但是,我更愿意写

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

val = bar.member;

对于我是试图从结构中还是从指向结构的指针中提取成员",这一点没有歧义.但是很容易使用错误的运算符,尤其是在重构代码时.(例如,也许我正在对 foo 进行一些复杂的操作,所以我将代码移到一个新函数中并将指针传递给 foo).我认为我不需要关心 foo 是否是指针;编译器可以担心细节.

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?

推荐答案

箭头"运算符是语法糖.bar->member(*bar).member 相同.差异的原因之一是可维护性.由于箭头运算符不同于点运算符,因此跟踪哪些变量是指针而哪些不是指针变得更加容易.可能总是使用 . 并让编译器尝试做正确的事情,但我怀疑这会使语言更简单.相信编译器会解释你的意思而不是你字面上写的通常结果很糟糕.

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天全站免登陆