递增/递减混淆

huangapple go评论79阅读模式
英文:

Increment/Decrement Confusion

问题

在这里减少代码时会发生什么:

temp[--countArray[getDigit(position, input[tempIndex], radix)]]

如果在这种情况下 temp 为 1:我们是先减少然后赋值为 0 吗?这个减少是多么即时?这常常在数组括号内让我感到困惑。

英文:

What is happening when we decrement the code here:

temp[--countArray[getDigit(position, input[tempIndex], radix)]]

If temp is 1 in this case: are we decrementing first so that we are assigning to 0? How immediate is this decrement? It always seems to confuse me within array brackets.

答案1

得分: 3

尝试在不同缩进级别上展开括号:

temp[                                                // 获取temp中的此索引
    --                                               // 减少1
    countArray[                                      // 获取countArray中的此索引
        getDigit(position, input[tempIndex], radix)  // 调用getDigit()
    ]
]

以人类可读的术语来说,它调用 getDigit() 来索引 countArray,然后递减该值并将其用于索引 temp


递减操作符 --xx-- 不同,因为它们返回的内容不同。在操作结束时,x 的值始终比之前小1,但 --x 返回 x 的新值,而 x-- 返回被递减之前 x 的旧值。对 ++xx++ 也适用相同规则。

英文:

Try unpacking the brackets on different levels of indentation:

temp[                                                // get this index in temp
    --                                               // decrement by 1
    countArray[                                      // get this index in countArray
        getDigit(position, input[tempIndex], radix)  // call getDigit()
    ]
]

In human-readable terms, it calls getDigit() to index into countArray, then decrements that value and uses it to index into temp.


The decrement operator --x is different from x-- because of what it returns. By the end of the operation, x always ends up as one less than it was, but --x returns the new value of x, while x-- returns the old value of x from before it was decremented. The same applies for ++x and x++.

答案2

得分: 1

让我将其分解一些。以下是与上述内容等效的一些代码:

int digit = getDigit(position input[tempIndex] radix);
countArray[digit]--;
int count = countArray[digit];
temp[count] // 用该值执行一些操作

顺便提一下,这经典地说明了为什么不应该为了简洁而牺牲清晰度。

英文:

Let me break this down some. Here's some code that's equivalent to above:

int digit = getDigit(position, input[tempIndex], radix);
countArray[digit]--;
int count = countArray[digit];
temp[count] // Do something with the value

Incidentally, this is a classic illustration of why you shouldn't sacrifice clarity to brevity.

huangapple
  • 本文由 发表于 2020年10月20日 21:30:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64446219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定