-4

In C

i = 7;
j = i++ * ++i; // outputs 64?

according to precedence post increment comes first so

it should be 7*9. Point out my mistake. Can you please provide me a resource where i can learn in detail and understand how these things work, that is the order of evaluation and all.

Anis_Stack
  • 3,306
  • 4
  • 30
  • 53
Ignited
  • 771
  • 3
  • 7
  • 21
  • 1
    I daresay this question has been asked hundreds of times on SO for C and C++. – Fred Larson Feb 24 '14 at 16:35
  • If you ever include this code (or anything that vaguely resembles it) you should be flogged to within an inch of your life. Why would it even occur to you to write something like this? And, no crap about "I'm learning c and want to understand post and prefix operators". – KevinDTimm Feb 24 '14 at 16:39
  • @KevinDTimm It was asked in one of of my exam. – Ignited Feb 24 '14 at 16:44
  • That's awful - undefined behavior doesn't have an answer - except that the result is undefined. – KevinDTimm Feb 24 '14 at 17:33
  • @KevinDTimm: Maybe the exam question was about undefined behavior. If classes covered examples like this being undefined behavior, that would be a very good thing. – Fred Larson Feb 24 '14 at 18:22
  • @FredLarson - OP says answer s/b 7*9 - so, either the exam is wrong in not accepting 'undefined behavior' or the OP has not been taught correctly. – KevinDTimm Feb 24 '14 at 18:25
  • 1
    @KevinDTimm: I don't know if that came from the exam itself or from the OP's assumption. But yes, if the exam was expecting any correct answer other than undefined behavior, that's terrible. – Fred Larson Feb 24 '14 at 18:28
  • The question came in exam. Answers keys are not yet out. I ran this program in couple of compilers and all gave same output 64, so I asked the question. I am taking 101 course, cant expect me to catch these undefined behaviors. – Ignited Feb 25 '14 at 11:45
  • @Ignited If the course was about the C language I would certainly expect you to catch those errors. – pmr Feb 25 '14 at 17:02
  • @pmr yeah then probably am not working hard. Perhaps you can guide me the way? – Ignited Feb 26 '14 at 01:52
  • http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list get one from the beginner category and work through it. – pmr Feb 26 '14 at 11:03

1 Answers1

0

Your problem is that there is no sequence point in the above. See Undefined behavior and sequence points

So you have no control over the order in which the two increments of i occur (just whether you are are returned the incremented number or the number before the increment). This is thus undefined behaviour.

For instance, it could execute the ++i first, returning 8, then the i++, also returning 8, and give you 64. As it is undefined behaviour, technically you can get any result.

Community
  • 1
  • 1
abligh
  • 24,573
  • 4
  • 47
  • 84