关于java和c中的++运算符的异同
在自加和自减参加的混合运算中(除自加和自减外还有别的运算),需要考虑自加和自减优先级。
自加和自减:最终的结果是给某个变量中+1或-1。
自加和自减运算规律:
- 如果++或–在变量的右侧,会将++或–左侧变量空间中的数据临时保存,然后给++或–左侧变量空间中+1或-1,这时表示++或–运算结束,然后将临时空间中的数据再参与其他运算。
- 如果++或–在变量的左侧,直接给++或–对应的变量+1或-1,然后将运算后的变量参与别的运算。
- 如果在一个运算中只有++或–,不考虑上述的规律,直接+1或-1
int x = 4;
int y = x++;
System.out.println("x = " + x);//5
System.out.println("y = " + y);//4
int a = 4;
int b = ++a;
System.out.println("a = " + a);//5
System.out.println("b = " + b);//5
//这里是不一样的地方
int i = 3;
i = i++;
System.out.println("i = " + i);//3,C语言执行后应该是4
int j = 3;
j = ++j;
System.out.println("j = " + j);//4
int m = 3;
m++; // ++m;
System.out.println("m = " + m);//4
int n = 3;
System.out.println("n = " + n++ ); //3, 输出之后n才+1
System.out.println("n = " + n);//4
所以:i++中参与外部运算的是临时空间的值,而自增的是变量本身存储的值。i = i++;中i先创造一个临时空间,值为3,然后i本身空间的值自增为4,再把临时空间的值3赋给自己,最终结果还是为3