gpt4 book ai didi

java - 为什么有前缀/后缀++而没有前缀/后缀+=?

转载 作者:太空狗 更新时间:2023-10-29 19:41:03 28 4
gpt4 key购买 nike

这似乎是一个愚蠢的问题,但为什么在许多语言中存在 ++-- 运算符的前缀和后缀版本,但是没有类似 +=-= 等其他运算符的前缀/后缀版本?例如,如果我能写出这段代码:

myArray[x++] = 137; // Write 137 to array index at x, then increment x

我应该能写出类似的东西

myArray[5 =+ x] = 137; // Write 137 to array index at x, then add five to x

当然,这样的算子是不存在的。是否有一个原因?这在 C/C++/Java 中似乎是一种奇怪的不对称。

最佳答案

我猜有几个原因,我认为其中权重较高的可能是:

  • 可能没有想到有太多真实的用例(早期的一些语言设计者甚至可能没有想到)
  • 前/后增量直接映射到机器操作(至少在几台机器上),所以他们找到了进入语言的方式(更新:事实证明这不完全正确,即使在计算中通常这样认为传说。见下文)。

话又说回来,虽然前/后/递增/递减运算符的想法可能受到机器操作的影响,但看起来它们并没有专门用于利用这些操作的语言。以下是丹尼斯·里奇 (Dennis Ritchie) 对他们的评价:

http://cm.bell-labs.com/cm/cs/who/dmr/chist.html

Thompson went a step further by inventing the ++ and -- operators, which increment or decrement; their prefix or postfix position determines whether the alteration occurs before or after noting the value of the operand. They were not in the earliest versions of B, but appeared along the way. People often guess that they were created to use the auto-increment and auto-decrement address modes provided by the DEC PDP-11 on which C and Unix first became popular. This is historically impossible, since there was no PDP-11 when B was developed. The PDP-7, however, did have a few `auto-increment' memory cells, with the property that an indirect memory reference through them incremented the cell. This feature probably suggested such operators to Thompson; the generalization to make them both prefix and postfix was his own. Indeed, the auto-increment cells were not used directly in implementation of the operators, and a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1.

关于java - 为什么有前缀/后缀++而没有前缀/后缀+=?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4636802/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com