这可能看起来像一个愚蠢的问题,但为什么在许多语言中存在和 – 运算符的前缀和后缀版本,但没有类似的前缀/后缀版本的其他运算符,如=或 – =?例如,似乎我可以编写此代码:
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.