你以前试过这个吗?
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
输出:10。
但是对于
static void Main(string[] args)
{
int x = 10;
x++;
Console.WriteLine(x);
}
输出:11。
有人能解释一下为什么会是这样吗?
你以前试过这个吗?
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
输出:10。
但是对于
static void Main(string[] args)
{
int x = 10;
x++;
Console.WriteLine(x);
}
输出:11。
有人能解释一下为什么会是这样吗?
X++会先将值加1,然后返回它的旧值。
因此,在这种情况下:
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
你在11处只有短暂的一刻,之后它回到了10,因为(x++)的返回值是10。您也可以通过以下方式获得相同的结果:static int plusplus(ref int x)
{
int xOld = x;
x++;
return xOld;
}
static void Main(string[] args)
{
int x = 10;
x = plusplus(x);
Console.WriteLine(x);
}
值得一提的是,如果你执行以下操作,你将会得到预期的结果 11:
static void Main(string[] args)
{
int x = 10;
x = ++x;
Console.WriteLine(x);
}
x = x++
中,你首先提取 x
的旧值以在评估右侧表达式(在此情况下为 'x')时使用;然后,你将 x
加 1。最后,你通过赋值语句,将表达式的结果(10)分配给 x
。var tmp = x;
x++;
x = tmp;
这相当于在C#中使用x = x++
的代码。
x++ 的行为是将 x 增加 1,但返回增加前的值。这也就是为什么它被称为后缀自增。
因此,x = x++ 简单来说会:
1. 返回 x 原始的值,然后
2. 将 x 增加 1,然后
3. 将 x 的原始值(在步骤 1 中返回)赋值给 x。
x = 10
x = ++x
x
最终将等于11。
x++;
以下是它的功能:
int returnValue = x;
x = x+1;
return returnValue;
正如你所看到的,原值被保存,x被递增,然后原值被返回。
这样做的结果是将值10保存在某个地方,将x设置为11,然后返回10,这会导致x被重新设置为10。请注意,在几个周期内(假设没有编译器优化),x实际上确实变成了11。
int x = 10;
X是一个容器,包含一个值10。
x = x++;
1) increment the value contained in x
now x contains 11
2) return the value that was contained in x before it was incremented
that is 10
3) assign that value to x
now, x contains 10
Console.WriteLine(x);
并且,毫不意外地,它会打印出10。
我知道已经有很多答案和一个被接受的答案,但我仍然想要提出我的意见来展示另一种观点。
我知道这个问题是关于C#的,但我认为对于像后缀运算符这样的东西,它的行为与C并没有不同:
int main(){
int x = 0;
while (x<1)
x = x++;
}
...
mov -8(rbp), 0 ; x = 0
L1:
cmp -8(rbp), 1 ; if x >= 1,
jge L2 ; leave the loop
mov eax, -8(rbp) ; t1 = x
mov ecx, eax ; t2 = t1
add ecx, 1 ; t2 = t2 + 1
mov -8(rbp), ecx ; x = t2 (so x = x + 1 !)
mov -8(rbp), eax ; x = t1 (kidding, it's the original value again)
jmp L1
L2:
...
t = x
x = x + 1
x = t
顺便提一下:开启任何优化都会得到类似于这样的汇编结果:
...
L1:
jmp L1
...
你要做的第一件事叫做“后增量”,意思是
int x = 10;
x++; //x still is 10
Console.WriteLine(x); //x is now 11(post increment)
当你执行 x = x++; 这一行时,x 的值仍然是10。如果你需要在这一行让 x 的值变成11,可以写成 ++x(我认为这被称为前缀自增,如果我错了请纠正我)... 或者写成 x++; 然后再写成 x = x++;
问题是,它是基于行还是基于语句的,也就是说,它会在分号之后递增吗?
也许我不正确,但是在一个类似的例子中更容易理解结果:
public static void main(String[] args) {
int x = 10;
int y = 0;
y = x + x++; //1, 2, 3, 4
x += x; //5
System.out.println("x = " + x + "; y = " + y); //6
}
让我们逐步看一下操作 y = x + x++:
现在让我们回到我们的例子并执行相同的步骤:
public static void main(String[] args) {
int x = 10;
x = x++; //1, 2, 3, 4
System.out.println(x); //5
}