c# - 为什么递增和递减是一元运算

标签 c# c++ .net c

看起来这是一个非常奇怪的问题,因为我读过很多文档,其中增量和减量是一元运算,没有任何解释。

我可能是错的,但 ++ii+=1 类似(如果没有任何覆盖):

int i = 1;
Console.WriteLine(++i); // 2

int j = 1;
Console.WriteLine(j+=1); // 2

在本例中,预自增是一个简单的语法糖,用于隐藏二元运算符 plus 和 1 作为第二个参数。

不是吗?

为什么递增和递减是独立的一元运算,它不只是带有预定义第二个参数且值为 1 的二元加运算符吗?

最佳答案

你的问题归结为为什么++--首先存在,而正常的+- 可以完成这项工作。

今天的编译器优化能力,其实都是历史原因造成的。 ++-- 可以追溯到 C 的早期(但不是最早)。 The Development of the C Language已故 C 语言作者 Dennis Ritchie 给出了一些有趣的历史见解:

Thompson went a step further by inventing the ++ and -- operators, which increment or decrement;

[...]

They were not in the earliest versions of B, but appeared along the way.

[...]

a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1.

因此,确切的原因似乎已经消失在历史的迷雾中,但 Ritchie 的这篇文章强烈表明增量和减量运算符的存在归因于早期编译器的性能问题。

当 C++ 发明时,与 C 的兼容性是其发明者 Bjarne Stroustrup 的主要设计目标之一,因此不用说,所有 C 运算符也存在于 C++ 中。正如 Stroustrup 本人在他的 FAQ 中所说的那样:

I wanted C++ to be compatible with a complete language with sufficient performance and flexibility for even the most demanding systems programming.

至于 C#,其发明者之一Eric Lippert once stated here on the Stack Exchange network C# 支持它们的唯一原因是与旧语言的一致性:

[...] these operators are horrid features. They're very confusing; after over 25 years I still get pre- and post- semantics mixed up. They encourage bad habits like combining evaluation of results with production of side effects. Had these features not been in C/C++/Java/JavaScript/etc, they would not have been invented for C#.

<小时/>

P.S.:C++ 很特别,因为正如您所提到的(即使使用了错误的“覆盖”一词),您可以重载所有这些运算符,这导致 ++-- 在许多程序员心目中的语义略有不同。它们有时读作“前进”(“后退”)或“向前迈出一步”(“后退一步”),通常使用迭代器。如果你看ForwardIterator C++ 中的概念,您会看到它只需要一元 ++

关于c# - 为什么递增和递减是一元运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284696/

相关文章:

c# - WCF 4.0 - 从 URL 或 POST 主体获取参数

c# - 是否存在与 ILMerge.exe 等效的 ILSplit.exe,或者如何实现?

c# - 如何在没有父元素的情况下将列表序列化为 XML

c# - 运算符 '!=' 不能应用于类型 'Task' 和 'int' 的操作数

c++ - 将临时值存储为某种数据类型时,算术运算的标准规则是什么?

PHP SOAP : Communication to a C++ application

.net - 无法捕获的 .NET 运行时 2.0 错误 - 用户机器 - 下一步是什么?

c# - 从 VB.NET 编码过渡到 C# 的好练习?

c# - 绑定(bind)到 ViewModel 的 ObservableCollection 类型的附加属性始终返回 null

c++ - %s 的 printf() 的不同运行时检查?