“双”分配 - 应该避免? [英] "Double" assignment - should it be avoided?

查看:144
本文介绍了“双”分配 - 应该避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑你有一些表达式

  i = j = 0 

假设这是您选择的语言中定义的。通常最好将它分成两个表达式,例如

  i = 0 
j = 0

我有时在库代码中看到这个。它看起来似乎没有买你很多简单,不应该执行任何更好的两个语句(虽然这可能是编译器依赖)。所以,有没有理由使用一个在另一个?还是只是个人喜好?我知道这听起来像一个愚蠢的问题,但是它让我很长时间了 - - )。

解决方案

不同的观点对任务。



第一种情况将赋值(至少是内部赋值)作为运算符(返回值的函数)。



第二种情况将赋值作为一个语句(一个命令来做某事)。



有些情况下赋值作为运算符,简洁,或在期望结果的上下文中使用。但我觉得很困惑。由于以下几个原因:




  • 分配运算符基本上是副作用运算符,现在对于编译器优化它们是个问题。在C和C ++等语言中,它们导致许多未定义的行为案例或未优化的代码。

  • 它不应该返回什么。赋值运算符返回已分配的值,或者返回已存储的地址的地址。

  • 对于 + = 的复合作业,它甚至更糟。



这个赋值语句应该返回一个赋值语句。作为一个陈述导致有时中间变量,但这是我看到的唯一的缺点。很清楚,编译器知道如何有效地优化连续的这样的语句。



基本上,我会尽可能避免赋值为运算符。提出的案例非常简单,而且并不令人困惑,但作为一般规则,我仍然更愿意。

  i = 0 
j = 0



<$ p $对于支持的语言,p> i,j = 0,0


Consider you have some expression like

i = j = 0

supposing this is well-defined in your language of choice. Would it generally be better to split this up into two expressions like

i = 0
j = 0

I see this sometimes in library code. It doesn't seem buy you much in terms of brevity and shouldn't perform any better than the two statements (though that may be compiler dependant). So, is there a reason to use one over the other? Or is it just personal preference? I know this sounds like a silly question but it's bugging me for a long time now :-).

解决方案

The two forms reflects different points of view on the assignment.

The first case treats assignment (at least the inner one) as an operator (a function returning a value).

The second case treats assignment as a statement (a command to do something).

There is some cases where the assignment as an operator has it's point, mostly for brevity, or to use in contexts that expect a result. However I feel it confusing. For several reasons:

  • Assignment operator are basically side effect operators, and nowadays it's a problem to optimize them for compilers. In languages like C and C++ they lead to many Undefined Behavior cases, or unoptimized code.
  • It is unclear what it should return. Should assignment operator return the value that as been assigned, or should it return the address of the place it has been stored. One or the other could be useful, depending on the context.
  • With composite assignments like +=, it's even worse. It is unclear if the operator should return the initial value, the combined result, or even the place it was stored to.

The assignment as a statement lead sometimes to intermediate variables, but that's the only drawback I see. It is clear and compilers know how to optimize efficiently successive such statements.

Basically, I would avoid assignment as operator whenever possible. The presented case is very simple and not really confusing, but as a general rule I would still prefer.

i = 0
j = 0

or

i, j = 0, 0

for languages that supports, parallel assignment.

这篇关于“双”分配 - 应该避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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