C#陷阱:int i = 10; i += i++; i = ?

王朝c#·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

参加某公司的笔试时的一道题目:int i = 10; i += i++; i = ?。当时我写了21。但当我在C#中写了如下代码测试时

static void Main(string[] args)

{

int i = 10;

i += i++;

Console.WriteLine(i);

Console.Read();

}

编译器告诉我,结果是20。为什么!我错了吗?我开始纳闷了。我赶紧用VC(Visual Studio.net2003)重新编了一段测试代码,如下:

int _tmain()

{

int i = 10;

i += i++;

Console::WriteLine(i);

Console::Read();

return 0;

}

这次,结果是21。奇怪了啊,为什么同样是i += i++,其结果是不一样的呢?

最终结论:语言差异

C# does have explicit rules around this behavior. (left to right)

C++ does not (problem of the C++ language, not the compiler)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航