pre增量VS阵列中增加后 [英] Pre increment vs Post increment in array
问题描述
我是新来的StackOverflow,这是我的第一篇文章。我学习编程,我已经从C语言开始。我读让我们C的书。我正想通过这个节目在这本书中。
I am new to Stackoverflow and this is my first post. I am learning programming and I have started from C language. I was reading Let us C book. And I was going through this program in that book.
main( )
{
int a[5] = { 5, 1, 15, 20, 25 } ;
int i, j, k = 1, m ;
i = ++a[1] ;
j = a[1]++ ;
m = a[i++] ;
printf ( "\n%d %d %d", i, j, m ) ;
}
我的理解是,它会打印我的2
,Ĵ为1
和米15
但不知何故,它被打印成我是3
,Ĵ为2
和米15
?为什么会这样呢?
But somehow it is printing as i as 3
, j as 2
and m as 15
? Why is it so?
下面是我的理解 -
Below is my understanding-
b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old value of ‘x’ is used.
b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value of ‘y’ gets modified before using it in a expression.
这有什么错在我的理解?
Is there anything wrong in my understanding?
推荐答案
您击中了要害。你的理解是正确的。 pre和后增量前pressions之间的区别就像是它的声音。 pre-增量是指设置或评估的前pression之前变量递增。后增量意味着前pression设置或评价,然后将变量被改变。人们很容易把它当做一个两个步骤。
You hit the nail on the head. Your understanding is correct. The difference between pre and post increment expressions is just like it sounds. Pre-incrementation means the variable is incremented before the expression is set or evaluated. Post-incrementation means the expression is set or evaluated, and then the variable is altered. It's easy to think of it as a two step process.
b = x++;
真的是:
b = x;
x++;
和
b = ++x;
真的是:
x++;
b = x;
编辑:你提供的例子(这可能扔你了)最棘手的部分是,有一个数组的索引,并将其值之间的巨大差异。
The tricky part of the examples you provided (which probably threw you off) is that there's a huge difference between an array index, and its value.
i = ++a[1];
这意味着递增存储在[1],然后将其设置为变量i的值。
That means increment the value stored at a[1], and then set it to the variable i.
m = a[i++];
这一种手段一套米的[I],然后递增i的值。两者之间的区别是pretty大的区别,可以在第一会比较混乱。
This one means set m to the value of a[i], then increment i. The difference between the two is a pretty big distinction and can get confusing at first.
二编辑:code分解
{
int a[5] = { 5, 1, 15, 20, 25 } ;
int i, j, k = 1, m ;
i = ++a[1] ;
j = a[1]++ ;
m = a[i++] ;
printf ( "\n%d %d %d", i, j, m ) ;
}
首先:
i = ++a[1];
在这一点上,我们知道一个[1] = 1(记住数组是零索引)。但是,我们首先增加了。因此,我= 2。
At this point we know a[1] = 1 (remember arrays are zero indexed). But we increment it first. Therefore i = 2.
j = a[1]++;
记住我们递增一个[1]之前,因此它是目前2.我们设置J = 2,然后将其递增到3。因此J = 2和现在一[1] = 3
Remember we incremented a[1] before, so it is currently 2. We set j = 2, and THEN incremented it to 3. So j = 2 and now a[1] = 3.
m = a[i++];
我们知道I = 2,所以我们需要设置M = A [2],然后递增我。在这个前pression结束时,M = 15,且i = 3
We know i = 2. So we need to set m = a[2], and then increment i. At the end of this expression, m = 15, and i = 3.
在总之,
i = 3, j = 2, m = 15.
这篇关于pre增量VS阵列中增加后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!