tags:

views:

188

answers:

3

iS THIS TRUE OR FALSE ? explain?

i++ = ++i

+4  A: 

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.)

Charlie Martin
C and C++ absolutely define what happens when ++ occurs within an expression. You can read the standard, or here's a relevant wiki page: http://en.wikipedia.org/wiki/Sequence_point
Paul Hankin
Yes, dear, and if you look carefully at your reference, you'll see that assignment in this context is *not* a sequence point.
Charlie Martin
If it's undefined behaviour the list of possibilities is endless and *not* restricted to the list of "sensible" options. (http://c-faq.com/expr/evalorder4.html)
awoodland
`++i++` ? Now there's something I've never tried!
Zabba
@awoodland fair enough; I should have said "some of the possibilities are" instead of implying these were the only ones.
Charlie Martin
+1  A: 

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.

awoodland
+1  A: 

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
Flinsch