-6

The very amazing and shocking logical problem occur which simple coding in c++.

See the following two chunk of code.

code 1

int m = 5, n = 0;
n = m++ * ++m;
//This print m = 7 and n = 36
//Which is logically wrong

code 2

int m = 5;
int n = m++ * ++m;
//This print m = 7 and n = 35
//Which is logically right

As we think logically the code block 2 gives right answer, but the amazing or magic thing is that what is wrong with code block1?

As part code its same, just we declared int n earlier.

May be some compile!!!!!!

  • 2
    `m++ * ++m` is *undefined behaviour*. There is nothing "logically wrong" about your output; it's your code that's broken. – Cairnarvon Jun 01 '13 at 18:38
  • I guess a valid question is: why is this compiler implementation working this way. – Elazar Jun 01 '13 at 18:45
  • @RaymondChen, you did not answer my question. The implementation could have spawned a Tic-Tac-Toe game, but it didn't. – Elazar Jun 01 '13 at 18:49
  • 1
    Don't think this question deserved downvotes - maybe marked / closed as a duplicate wrt sequence points and undefined behaviour. This stuff can be surprising to a novice (and new member) who wants some clarity. – Brett Hale Jun 01 '13 at 18:55

2 Answers2

3

Check http://en.cppreference.com/w/cpp/language/eval_order especially the part which discusses "Undefined behavior". Basically it's not a bug in the compiler. The language says what you're doing is undefined.

Guillaume
  • 2,044
  • 12
  • 11
0

Besides the "undefined behavior" part, which is important, there's nothing illogical here. Assuming the evaluation is from right to left:

++m -> value is 6, m is 6
m++ -> value is 6, m is 7
6*6 = 36
Elazar
  • 20,415
  • 4
  • 46
  • 67