前缀和后缀运算符有什么区别? [英] What is the difference between prefix and postfix operators?
问题描述
以下代码打印的值为 9.为什么?这里 return(i++)
将返回一个值 11 并且由于 --i
值应该是 10 本身,谁能解释一下这是如何工作的?
The following code prints a value of 9. Why? Here return(i++)
will return a value of 11 and due to --i
the value should be 10 itself, can anyone explain how this works?
#include<stdio.h>
main()
{
int i= fun(10);
printf("%d
",--i);
}
int fun (int i)
{
return(i++);
}
推荐答案
++
的后缀和前缀版本之间存在很大区别.
There is a big difference between postfix and prefix versions of ++
.
在前缀版本(即++i
)中,i
的值递增,表达式的值为newstrong> i
的值.
In the prefix version (i.e., ++i
), the value of i
is incremented, and the value of the expression is the new value of i
.
在后缀版本(即i++
)中,i
的值是递增的,但表达式的值是原始i
的值.
In the postfix version (i.e., i++
), the value of i
is incremented, but the value of the expression is the original value of i
.
我们一行一行地分析下面的代码:
Let's analyze the following code line by line:
int i = 10; // (1)
int j = ++i; // (2)
int k = i++; // (3)
i
设置为10
(简单).- 这一行有两件事:
i
增加到11
.- 将
i
的new 值复制到j
中.所以j
现在等于11
.
i
is set to10
(easy).- Two things on this line:
i
is incremented to11
.- The new value of
i
is copied intoj
. Soj
now equals11
.
i
增加到12
.- 将
i
(即11
)的原始值复制到k
中.所以k
现在等于11
.
i
is incremented to12
.- The original value of
i
(which is11
) is copied intok
. Sok
now equals11
.
所以在运行代码之后,i
将是 12,但 j
和 k
都是 11.
So after running the code, i
will be 12 but both j
and k
will be 11.
同样的东西也适用于 --
的后缀和前缀版本.
The same stuff holds for postfix and prefix versions of --
.
这篇关于前缀和后缀运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!