有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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中,这似乎是一种奇怪的不对称现象


共 (6) 个答案

  1. # 1 楼答案

    因为--and++运算符映射到CPU中的inc(rement)和dec(rement)指令(除了加法和减法),并且这些运算符被假定为映射到指令,因此它们作为单独的运算符存在

  2. # 2 楼答案

    我想有几个原因,我认为更重的原因可能是:

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

    再说一次,虽然前置/后置/递增/递减运算符的想法可能受到机器操作的影响,但看起来它们并不是专门为了利用这些特性而被放入语言中的。以下是丹尼斯·里奇对他们的看法:

    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.

  3. # 3 楼答案

    我猜是因为它太神秘了。 有些人认为,即使是++/-也应该避免,因为它们会造成混乱,并导致大多数缓冲区溢出错误

  4. # 4 楼答案

    只要y没有副作用:

    #define POSTADD(x,y) (((x)+=(y))-(y))
    
  5. # 5 楼答案

    java和C++有前、后增量和减量运算符,因为C有它们。C有它们,因为C主要是为PDP-11编写的,PDP-11有INCDEC指令

    在当时,优化编译器并不存在,所以如果你想使用单周期增量操作符,要么你为它编写汇编程序,要么你的语言需要一个显式操作符;C、 作为一种可移植的汇编语言,具有显式的递增和递减运算符。而且++ii++之间的性能差异现在很少重要,但在1972年确实重要

    请记住,C已经快40岁了

  6. # 6 楼答案

    我来做个假设。有很多++i/i++的用例,在许多情况下,特定类型的增量(pre/post)会有所不同。我不知道我见过多少次像while (buf[i++]) {...}这样的代码。另一方面,+=的使用频率要低得多,因为一次将指针移动5个元素几乎没有意义

    所以,没有一个足够普遍的应用程序,后缀和前缀版本的+=之间的差异会很重要