为什么自增自减是一元运算

Why increment and decrement are unary operations

看起来这是一个很奇怪的问题,因为我看了很多文档,其中递增和递减是一元操作,没有任何解释。

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

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

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

在这种情况下,预增量是简单的语法糖,用于隐藏二元运算符加号和 1 作为第二个参数。

不是吗?

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

答案很简单。

一元运算意味着运算符将只对操作数进行运算。

next i++ 和 i+=1 都是不同的动作

-> 当 i++ 将执行你时,编译器将进入变量位置并增加值。

-> i+=1 执行 i 并且 1 将加载到 register/temparory 变量中并且完成加法操作并将新值复制到 i 地址位置。

所以与 i+=1 比较将是与 i++ 相比的成本。

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

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

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++ 很特别,因为正如您所提到的(即使 "overriding" 这个词不正确),您可以 重载 所有这些运算符,这导致 ++-- 在许多程序员的脑海中呈现出略微不同的语义。它们有时读作 "go ahead" ("go back") 或 "make one step forward" ("make one step backward"),通常带有迭代器。如果您查看 C++ 中的 ForwardIterator 概念,您会发现它只需要一元 ++