pre Decrement vs. post Decrement

那年仲夏 提交于 2019-11-26 21:56:49

问题


When should I use pre decrement and when to use post decrement?

and for the following code snippet, should I use pre or post decrement.

static private void function(int number)
{
    charArr = new char[number];
    int i = 0;
    int tempCounter;
    int j = 0;
    while(charrArr!=someCharArr)
    {
        tempCounter = number - 1;
        password[tempCounter] = element[i%element.Length];
        i++;
        //This is the loop the I want to use the decrementing in.
        //Suppose I have a char array of size 5, the last element of index 5 is updated
        //in the previous statement.
        //About the upcoming indexes 4, 3, 2, 1 and ZERO.
        //How should I implement it?
        // --tempCounter or tempCounter-- ?
        while (charArr[--tempCounter] == element[element.Length - 1])
        {
        }
    }
}

回答1:


You use pre-decrement if you want to decrement the variable before the value is passed on to the remaining expression. On the other hand, a post-decrement evaluates the expression before the variable is decremented:

int i = 100, x;
x = --i;                // both are 99

and

int i = 100, x;
x = i--;                // x = 100, i = 99

The same obviously is true for increments.




回答2:


you should have ++i; (not that it matters), and should have tempCounter-- Otherwise you will miss the "first" index of charArr



来源:https://stackoverflow.com/questions/4531870/pre-decrement-vs-post-decrement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!