Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 727
Misam Avatar asked Dec 08 '22 23:12

Misam


1 Answers

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.

like image 180
Mark Byers Avatar answered Dec 21 '22 23:12

Mark Byers