后前润肤 [英] post-pre increament
问题描述
亲爱的Al,
早上好.
对于for循环中的后无声运算符和前无声运算符,我面临一些概念上的疑问.
请遵循以下代码:
Dear Al,
Very Good morning.
I am facing some conceptual doubts in post increament and pre increament operators in for loop.
Kindly follow the code below:
for(int i=0;i<5;i++)
{
cout<<i<<endl;
}
输出:
output:
0
1
2
3
4
再次,
Again,
for(int j=0;j<5;++j)
{
cout<<j<<endl;
}
输出将相同.
我的问题是代码的处理是如何进行的?
++j
& i++
都具有相同的输出,怎么办?
Output will be same.
My question is how the processing of the code takes place?
++j
& i++
both are possessing the same output, how?
推荐答案
++i
和i++
的副作用是相同-i
的值增加.但是表达式的值不同.
The side-effect of++i
andi++
is the same - the value ofi
is incremented. However the value of the expression is different.
int x = 2;
int j = ++x; // now x == 3 and j == 3
int q = x++; // now x == 4 and q == 3
因此,前增量是使用前的增量,后增量是使用后的增量.
So pre-increment is increment before use, and post-increment is increment after use.
了解前和后增量的方式工作中,我们需要一个不同于您编写的示例;看这个:
To understand how pre and post increment work, we need an example different from the one you wrote; look at this:
int i = 0;
int j = i++;
int k = ++i;
printf("i = %d\nj = %d\nk = %d\n", i, j, k);
这将产生如下输出:
This will produce an output like:
i = 2
j = 0
k = 2
语句int j = i++;
的意思是:首先将i
的值分配给j
,然后将i
递增(与int j = i; i = i + 1;
相同)
语句int k = ++i;
的意思是:首先递增i
,然后将i
的值赋给k
(与i = i + 1; int k = i;
相同)
The statement int j = i++;
means: first assign to j
the value of i
and after increment i
(it is the same than int j = i; i = i + 1;
)
The statement int k = ++i;
means: first increment i
and after assign to k
the value of i
(it is the same than i = i + 1; int k = i;
)
for
行中的第二个分号-
将在第一个循环主循环之后处理:)
因此,您可以感觉到++ x&的区别. x ++(--x& x--)
例如以下几行:
The part after the second semicolon in afor
line -
will be processed after the first loop primary :)
So you can feel the difference of ++x & x++ (--x & x--)
for example by the following lines:
{
// one result
int i = 5;
do {
// after-call decrement
printf("%d\n", i--);
} while(i);
// another result
printf("\n");
i = 5;
do {
// pre-call decrement
printf("%d\n", --i);
} while(i);
}
这篇关于后前润肤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!