-3

Possible Duplicate:
Undefined Behavior and Sequence Points

i am wondering from the ending result between this 2 chunk of code one in c++ other in c#. these two chunks give differents result which doesnt make any sense any explanation will be helpful.

  //c++
  int x=0;
  x=x++ + ++x;// result=3

  //c#
  int x=0;
  x=x++ + ++x;// result=2 (logical answer)
Community
  • 1
  • 1
Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44

2 Answers2

6

In C++ this is undefined behaviour as has been discussed here a gazillion times. In C# the behaviour is well defined. With undefined behaviour any result is possible.

No matter whether or not the behaviour is well defined or not, you should never write code like this.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
4

In C++ I believe the behaviour is unspecified.

In C# the order of evaluation is more tightly specified in general, and the answer is guaranteed.

In either language, code like this should be avoided. It's hard to understand, and is generally written to show how "smart" the author is, rather than to create code which can be easily seen to be correct and changed later if necessary.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @HusseinX: The reason for what, exactly? You've got two different languages, with two different specifications. In some cases, operations which look like they will give the same answer won't. That should be *expected* with two different languages. – Jon Skeet Nov 02 '11 at 17:35
  • @HusseinX Both Jon and I have explained the reason. Your code is UB in C++. – David Heffernan Nov 02 '11 at 17:36