Search code examples
javaincrementdecrement

Increment/Decrement Confusion


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.


Solution

  • 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++.