C# 预减量与后减量
何时应使用预减量,何时使用后减量 对于下面的代码片段,我应该使用前减量还是后减量C# 预减量与后减量,c#,decrement,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; pa
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])
{
}
}
}
你应该有
++i
(这并不重要),并且应该具有临时计数器--
,否则您将错过charArr的“第一个”索引如果您想在值传递到剩余表达式之前递减变量,请使用预递减。另一方面,后减量在变量减量之前对表达式求值:
int i = 100, x;
x = --i; // both are 99
及
增量显然也是如此。在C#,iirc中,增量/减量前后的速度没有差别。我正在更新第二个while循环中的字符值,从
最后一个索引-1
到索引=0
。因此,在循环的条件下,我应该使用tempCounter--
还是--tempCounter
?对于内置时间,这可能是正确的,但对于定义这些运算符的用户类,这通常是不正确的<代码>--i代码>可能会更快,但决不会比i--代码>。但我们都知道一句话,像i--代码>将被编译器优化,特别是当我是int类型时。@sikas我将使用while(tempCounter>0){charArr[tempCounter-->=/*value*/}
因此charArr[--tempCounter]
在while循环的条件下,它的值将不同于charArr[tempCounter-->
。这将在检查条件之前减小临时计数器的值。@sikas:我不明白你的第二行。这两个版本将导致在循环中使用相同的值。pre/post减量只影响而-expression中发生的事情。就您的代码而言,我想它应该是tempCounter=number
、密码[tempCounter-1]
和字符[--tempCounter]
尽管while
-循环将在未初始化的数组上工作,并且tempCounter
可能会变为负数。可能存在重复的
int i = 100, x;
x = i--; // x = 100, i = 99