Search code examples
c#c++sequence-points

Same code, different output in C# and C++


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!!


Solution

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