简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM