关键字: j=j++ 的问题 看《JAVA解惑》的谜题25:
- public class Increment {
- /**
- * @param args
- */
- public static void main(String[] args) {
- int j = 0 ;
- for ( int i = 0 ; i <= 100 ; i++) {
- j = j++;
- }
- System.out.println(j);
- }
- }
public class Increment {
/**
* @param args
*/
public static void main(String[] args) {
int j = 0;
for (int i = 0; i <= 100; i++) {
j = j++;
}
System.out.println(j);
}
}
程序打印的结果是0,解释为:j=j++;这一句操作等于如下的操作
- int temp = j;
- j= j+1 ;
- j= temp;
int temp = j;
j= j+1;
j= temp;
所以无论程序执行了多少遍,j还是等于0。
而我将这相同的例子转化成C、C++语言去执行,则得到的结果完全不一样。
在C、C++中会得到我们所想象的值:j=100。
不要在单个的表达式中对相同的变量赋值超过一次
PS:前两天写代码,我还真出现了这个问题,写成了j=j++