pre decrement和。后减法

时间:2010-12-25 22:10:07

标签: c# 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])
        {
        }
    }
}

2 个答案:

答案 0 :(得分:4)

如果要在将值传递给剩余表达式之前递减变量,则使用预递减。另一方面,后递减在变量递减之前计算表达式:

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

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

增量显然也是如此。

答案 1 :(得分:0)

你应该++i;(并不重要),并且应该有tempCounter--否则你会错过charArr的“第一”索引

相关问题