今天看<>时突然发现一个关于 i++ 这种后缀表达式的小问题,与C/C++中的表现居然存在差别
public class Increment{
public static void main(String[] args){
int j = 0;
int i = 0;
for( i = 0; i < 100; i++ )
j = j++;
System.out.println(" j = " + j);
}
}
javac Increment.java
java Increment
得到的结果居然为 j = 0;
解析:The value of the expression j++ is the original value of j before it
was incremented. therefore, the preceding assignment first save the value of
j, the sets j to its value plus, and finally, resets j back to its original
value. In other words, the assigment is equivalent ot this sequence of statement:
int tmp = j;
j = j + 1;
j = tmp;
The Lession is : Do not assign to the same variable more than once in a single
expression
but in C
//file t4.c
int main(void){
int j = 0;
int i = 0;
for( i = 0; i < 100; i++)
j = j++;
printf("j= %d\n", j);
}
cc t4.c
./a.out
the output is: j = 100;
what is the problem?
阅读(1536) | 评论(0) | 转发(0) |