(注意:我不是在问前增量与后增量的定义,或者它们在 C/C++ 中的使用方式。因此,我不认为这是一个重复的问题。)
C 语言的开发者(Dennis Ritchie 等人)出于非常充分的理由创建了递增和递减运算符。我不明白的是,为什么他们决定区分前后递增/递减?
我的感觉是,这些运算符在开发 C 时比现在有用得多。大多数 C/C++ 程序员使用其中一种,而来自其他语言的程序员发现今天的区别很奇怪和令人困惑(注意:这完全基于轶事证据)。
他们为什么决定这样做,在计算上发生了什么变化导致这种区分在今天不再那么有用?
备案,两者的区别可以在C++代码中看出:
int x = 3;
cout << "x = 3; x++ == " << x++ << endl;
cout << "++x == " << ++x << endl;
cout << "x-- == " << x-- << endl;
cout << "--x == " << --x << endl;
将作为输出给出
x++ == 3
++x == 5
x-- == 5
--x == 3
最佳答案
以 1 递增和递减在当时的硬件中得到广泛支持:单个操作码,而且快速。这是因为“递增 1”和“递减 1”是代码中非常常见的操作(直到今天都是如此)。
后递减和预递减形式仅影响此操作码在生成的机器代码中插入的位置。从概念上讲,这模拟了“使用结果之前或之后增加/减少”。在单个语句中
i++;
没有使用“之前/之后”的概念(因此它与 ++i;
的作用相同),但在
printf ("%d", ++i);
是的。如今,这种区别与设计语言 C 时一样重要(这个特殊的习语是从其名为“B”的前身复制而来的)。
来自 The Development of the C Language
This feature [PDP-7's "`auto-increment' memory cells"] probably suggested such operators to Thompson [Ken Thompson, who designed "B", the precursor of C]; the generalization to make them both prefix and postfix was his own. Indeed, the auto-increment cells were not used directly in implementation of the operators, and a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1.
感谢@dyp 提及这份文件。
关于c++ - C语言有前置自增和后置自增的历史原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429753/