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

落爺英雄遲暮 提交于 2020-01-14 10:33:10

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/10908988/same-code-different-output-in-c-sharp-and-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!