pre decrement vs. 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]) { } } } 

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

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

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

增量显然也是如此。

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