同样的代码,在C#和C不同的输出++ [英] Same code, different output in C# and C++
本文介绍了同样的代码,在C#和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);
}
}
}
输出:27
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;
}
输出:76
Output:76
同样的代码differernt输出,可有人告诉为什么会这样?
帮助感激!
Same code has differernt output, can somebody tell why is this so ? Help appreciated!!
推荐答案
在C#代码中被明确界定,并等同于以下内容:
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))));
这是大致相同的:
a = a - (b = (b * 3) - (a * 2));
或者更简单的:
b = (b * 3) - (a * 2);
a -= b;
不过,在C ++代码中给出了不确定的行为。谁也不能保证在所有关于什么都行。
However, in C++ your code gives undefined behaviour. There is no guarantee at all about what it will do.
这篇关于同样的代码,在C#和C不同的输出++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文