4

C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 11;
            int b = 2;
            a -= b -= a -= b += b -= a;
            System.Console.WriteLine(a);
        }
    }
}

Output:27

C++:

#include "stdafx.h"
#include<iostream>

int _tmain(int argc, _TCHAR* argv[])
{
       int a = 11;
       int b = 2;
       a -= b -= a -= b += b -= a;
       std::cout<<a<<std::endl;
       return 0;
}

Output:76

Same code has differernt output, can somebody tell why is this so ? Help appreciated!!

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
Misam
  • 4,320
  • 2
  • 25
  • 43

1 Answers1

14

In C# your code is well defined and is equivalent to the following:

a = a - (b = b - (a = a - (b = b + (b = b - a))));

The innermost assignments are not relevant here because the assigned value is never used before the variable is reassigned. This code has the same effect:

a = a - (b = b - (a - (b + (b - a))));

This is roughly the same as:

a = a - (b = (b * 3) - (a * 2));

Or even simpler:

b = (b * 3) - (a * 2);
a -= b;

However, in C++ your code gives undefined behaviour. There is no guarantee at all about what it will do.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 7
    Absolutely correct. The short answer: C# != C != C++. The longer answer: requires an understanding of ["sequence points"](http://blogs.msdn.com/b/oldnewthing/archive/2007/08/14/4374222.aspx) – paulsm4 Jun 06 '12 at 06:15
  • 1
    @paulsm4 an important note though is that C is a subset of C++, C++ is not a subset of C#. – chacham15 Jun 06 '12 at 06:28
  • 14
    @chacham15 No, C is *not* a subset of C++. [For example](http://stackoverflow.com/questions/5337370/), `int a; int a;` is valid C, but invalid C++. – fredoverflow Jun 06 '12 at 06:31
  • @FredOverflow is that the only difference? it just seems like such a nitpick to point that out. – chacham15 Jun 07 '12 at 21:36
  • 2
    @chacham15 No, [of course not](http://stackoverflow.com/questions/1201593/), tentative definitions are just one of many examples. – fredoverflow Jun 08 '12 at 08:34