问题
I don't know if this is compiler specific but when I tried running the two expressions in DevC++
When i=c=b=0;
i=i++ + ++c
gives 2
whereas i=++i + c++
gives 1
But
b=i++ + ++c
and
b=++i + ++c
produces the result 1
for both expressions.
I do know that incrementing a variable twice in the same expression results in an undefined value according to the C standard specification but I'm curious how the compiler produces these output. Could someone please explain how and why?
回答1:
i++
and ++i
are completely different, i++
is post increment which means evaluate i
in the expression and then increment once its evaluated. ++i
means increment then evaluate the expression.
I see in your example you set i = ++i/i++
, this is undefined behavior as mentioned in a comment.
回答2:
i++ + ++c
, the c
is incremented (to 1), then 0 + 1
is stored in i
, and finally i
is incremented, giving 2
.
++i + c++
, the i
is incremented (to 1), then 1 + 0
is stored in i
, then c
is incremented.
That's how I would understand what the compiler did, but as everyone else is saying, don't count on this behavior elsewhere.
回答3:
Are you sure b = ++i + ++c = 1? or was it b = ++i + c++? Here is my explanation of your question.
i = i++ + ++c
(i = 0 + 1)++
i = 2
c = 1
i = ++i + c++
(i = 1 + 0)
i = 1
c = 1
回答4:
The C99 standard says explicitly (6.5, p2)
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.
The expressions i = ++i;
and i = i++;
both update i
twice, which is not allowed.
来源:https://stackoverflow.com/questions/6482035/difference-in-output-of-i-i-c-and-i-i-c