【问题标题】:pre Decrement vs. post Decrement预减量和。递减后
【发布时间】:2011-05-30 17:35:45
【问题描述】:

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

对于下面的代码sn-p,我应该使用前减量还是后减量。

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 可以变成负数。

标签: c# decrement


【解决方案1】:

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

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

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

对于增量显然也是如此。

【讨论】:

  • 所以 charArr[--tempCounter] 在 while 循环的条件下与 charArr[tempCounter--] 的值不同。这将在检查条件之前减少tempCounter
  • @sikas:我不明白你的第二行。两个版本都将导致在循环内使用相同的值。前/后减量只影响while-表达式中发生的事情。
【解决方案2】:

你应该有++i;(没关系),并且应该有tempCounter--否则你会错过charArr的“第一个”索引

【讨论】:

  • 在 C#、iirc 中,前后增量/减量对速度没有影响。
  • 我在第二个 while 循环中更新 charArr 的值,从 last index - 1index = ZERO。所以在循环的情况下我应该使用tempCounter--还是--tempCounter
  • 这对于内置时代可能是正确的,但对于定义这些运算符的用户类通常是不正确的。 --i; 可能更快,但绝不会比i--; 慢。但是我们都知道像i--; 这样的行将被编译器优化,尤其是当 i 是 int 类型时。
  • @sikas 我会用while(tempCounter > 0) { charArr[tempCounter--] = /* value */ }
猜你喜欢
  • 1970-01-01
  • 2017-01-28
  • 2017-07-05
  • 1970-01-01
  • 2018-08-08
  • 2020-01-03
  • 1970-01-01
  • 2015-08-25
  • 2021-06-22
相关资源
最近更新 更多