看起来这是一个非常奇怪的问题,因为我读过很多文档,其中增量和减量是一元运算,没有任何解释。
我可能是错的,但 ++i
与 i+=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 ofx=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/