c# - 程序输出的差异

标签 c# c++ operator-precedence

我有一个简单的代码片段,它在使用 C++ 编译器和 C# 编译器构建时显示不同的行为。

C#

static void Main(string[] args)
{
   int i = 0;
   i += i++;
   Console.WriteLine(i);
   Console.ReadLine();
}

i的结果是 0 。 从此链接复制。 For i = 0, why is (i += i++) equal to 0?

C++

int main() 
{
    int i = 0;
    i += i++;
    cout << i << endl;
}

i的结果是 1 .

我只是想知道为什么C#C++的代码输出存在差异。

最佳答案

C#、C++ 和 C 的设计者 made different decisions about how to handle order of evaluation而在 C# the order of evaluation如果从左到右:

Operands in an expression are evaluated from left to right.

副作用也是从左到右发生的。

在 C++ 中情况并非如此,draft C++ standard 1.9 部分程序执行 段落15 说:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

如果同一标量对象上的副作用相对于另一个副作用进行排序,则结果为 undefined behavior :

[...]If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.[...]

草案给出了未定义行为的示例:

i = i++ + 1; // the behavior is undefined

如果我们查看代码中的表达式:

i += i++;

这相当于:

i = i + i++ ;

我们现在可以清楚地看到它调用了未定义的行为,这意味着结果是不可预测且不可依赖的。

关于c# - 程序输出的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22714134/

相关文章:

c# - 在 C# 中,有没有办法为新数据类型编写自定义对象初始值设定项?

c# - 如何使用 ADO.NET 创建数据源而不是读取和操作数据源

c++ - 无法从排序类 C++ 访问元素

c++ - SendInput (C++) 不起作用

c - 为什么移位的优先级低于 C 中的加法和减法?

c# - InvalidOperationException : No authentication handler is registered for the scheme 'CookieSettings' . 是否忘记调用 AddAuthentication()

c++ - 需要在一些分配后打印一个字符串。但输出为空白。错误是什么?

PHP 似乎正在向后评估 if 语句

c - 为什么这些构造使用增量前和增量后未定义的行为?

c# - 如何向用户指示哪个 textBox 为空或 null?