pre Decrement与post Decrement的区别

4

什么时候应该使用前缀递减,什么时候应该使用后缀递减?

对于以下代码片段,我应该使用前缀递减还是后缀递减?

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])
        {
        }
    }
}

就你的代码而言,我猜应该是 tempCounter = number;password[tempCounter - 1]charArr[--tempCounter],尽管 while 循环将在一个未初始化的数组上工作,而且 tempCounter 可能会变成负数。 - sjngm
可能是What is the difference between ++i and i++的重复问题。 - TylerH
2个回答

5

如果你想在变量传递给剩余表达式之前将其减小,可以使用前缀递减。另一方面,后缀递减在变量递减之前评估表达式:

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

and

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

显然,增量也是如此。

因此,在 while 循环的条件中,charArr[--tempCounter] 的值将与 charArr[tempCounter--] 不同。这将在检查条件之前递减 tempCounter - sikas
1
@sikas:我不理解你的第二行。两个版本将导致循环内使用相同的值。前/后缀递减仅影响while表达式中发生的情况。 - sjngm

0

你应该使用++i;(虽然这并不重要),并且应该使用tempCounter--,否则你将会错过charArr的“第一个”索引。


在C#中,如果我没记错的话,前缀和后缀递增/递减对速度没有影响。 - Jeff Hubbard
我正在第二个 while 循环中更新 charArr 的值,从“最后一个索引-1”到“索引=ZERO”。因此,在循环的条件中,我应该使用 tempCounter-- 还是 --tempCounter - sikas
这可能适用于内置时间,但通常不适用于定义这些运算符的用户类。 --i; 可能更快,但永远不会比 i--; 慢。但我们都知道像 i--; 这样的代码行将被编译器优化,特别是当 i 的类型为 int 时。 - EnabrenTane
@sikas 我会使用 while(tempCounter > 0) { charArr[tempCounter--] = /* value */ } - EnabrenTane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接