为什么 int 类型的变量在许多语言中默认是有符号的?

Why variables of type int are signed by default in many languages?

C、C++、C#、Java、Rust等默认已签名int。大多数时候你需要无符号 变量 ,因为你必须表示可以小于零的东西的情况比处理自然数的情况要少。同样,无符号 变量 不必以 2 的补码形式进行编码,并且它们的最高有效位可用于额外的值范围。

考虑到所有这些,为什么语言的创造者会让整数默认签名?

Python 默认 signed INT pool 表示 -128 到 127(可能是另一个范围,并通过修改源代码,你可以使这个池更大或更小)以通过引用使用 INT。它使 Python 工作得更快,因为每次你需要一个超出该范围的 INT 时,它都必须新建一个 INT 对象。

而且,就个人而言,我通常使用负数作为 return 值来表示坏事。

放在一起,我认为使用小的负数有很多变化,它使 signed int default 有价值。

我认为你的基本说法是错误的。负数在现实生活中很常见。想想温度、银行账户余额、SO 问题和答案分数...在计算中对物理数据建模需要一种自然的方式来表达负数。

实际上,Brian Kernighan 和 Dennis Ritchie 在 C 编程语言 中的第二个示例是一个在华氏度和摄氏度之间转换温度的程序。这是他们第一个C语言数值应用的例子。

数组大小确实是正数,但指针偏移量在 C 中可能是负数。

Ada 等其他语言指定了数值变量的范围,但算术计算仍然假设在 0 处连续,并且暗含负数。

C 中指定的无符号算术实际上令人困惑:1U - 2U 大于 0,就像 -1U。将其设置为默认值太违反直觉了!

在此 post 中确实有人回答了您的问题: Default int type: Signed or Unsigned?

与 post 中接受的答案相同的引用:

On Unsigned Integers

Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider:

for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect.

So, document that a variable is non-negative using assertions. Don't use an unsigned type.

时光倒流很久:

  • 大约在 1960 年,FORTRAN、ALGOL 和 LISP 的第一个版本(仅)对整数(和实数)进行了签名。(COBOL 是主要的例外。)这同样适用于 70 年代的语言,例如Pascal 和 BCPL.

  • EDSAC (1949) 支持(仅)有符号数。

事实上,C 是第一种支持 无符号 整数的语言。

So ... why would creators of languages make ints signed by default?

嗯,一个原因是在 C 时代之前,有符号整数是唯一可用的类型。所以很自然地设为默认值。

另一个原因是需要签名数字的用例实际上比您意识到的要普遍得多。还有另一个 class 的用例,其中整数是否有符号并不重要。