开发者

i++ = ++i iS THIS TRUE OR FALSE ? explain? [closed]

开发者 https://www.devze.com 2023-01-23 00:27 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_如何学C Closed 12 years ago.

iS THIS TRUE OR FALSE ? explain?

i++ = ++i


No, it isn't. Either true OR false.

The problem is that C/C++ don't define when ++ happens within this expression.

So you have several possibilities:

  1. Add 1 to i for the ++i then store that back in i, then add again for thei++`.
  2. add 1 to i for the i++ and save thje result for later; add 1 to i for the ++i assign it to i and then put the saved value of i++ into i.
  3. Add 1 to i for the i++ and then assign the result of ++i on top of it.

It gets even better when you consider, say, i = ++i++;

(See the link in the comments. The technical issue with whether there is a "sequence point" there, at which point all side effects should be resolved. In this assignment, there's not one.)


It depends what it is you're actually getting at:

If you meant does the following expression evaluate to true:

i++ == ++i

then it's undefined behaviour because i is modified twice between sequence points.

If you meant: do i++; and ++i; do the same thing then the answer is sort of -- they both increment i. Where they differ however is if they are part of a larger statement, do they use the value before or after the increment.

In practice this means that i++ might possibly involve making a copy internally, in order to store the value before the increment, whilst ++i doesn't need to make such a copy.

If you were asking about i++ = ++i; as a statement on its own then it's not a valid statement for a more fundamental problem: the i++ cannot be the lefthand side of an assignment because of the "temporary" nature of its value.

See this link and this one for more discussion etc.


Just in case you don't know the difference between pre-increment and post-increment and you just formulated the question unintelligible:

i = 7;
printf("%d\n", i); // precondition: result 7
printf("%d\n", ++i); // PRE-INCREMENT: result 8 !!!
printf("%d\n", i); // postcondition: result 8

i = 7;
printf("%d\n", i); // precondition: result 7
printf("%d\n", i++); // POST-INCREMENT: result 7 !!!
printf("%d\n", i); // postcondition: result 8
0

精彩评论

暂无评论...
验证码 换一张
取 消