gpt4 book ai didi

c - Int 类型不应该是平台字长的大小吗?

转载 作者:太空狗 更新时间:2023-10-29 17:22:11 25 4
gpt4 key购买 nike

我听说过很多关于这个主题的相互矛盾的信息,但总的来说,我听说 Int 类型应该与平台字长有关,所以例如在 32 位机器中 Int 有 4 个字节。

除非我小时候开始在 DOS 上编码,否则我认为我的编译器已经使用了 32 位 Int,即使目标是 16 位处理器(如 286)需要经常使用 shorts...

今天为了好玩把自己的一个程序编译成64bit的,结果Int还是32bit的(短16bit,没测试长)。

我知道 C 标准定义了这个:short <= int <= long但我很好奇,发生了什么事?为什么每个人都决定为 int 使用一些任意大小?

最佳答案

C99 Rationale 用了很多词来解释为什么要引入long long,我引用了关于整数类型历史的部分,我认为它至少可以部分回答你的问题。

Rationale for International Standard — Programming Languages — C §6.2.5 Types

In the 1970s, 16-bit C (for the PDP-11) first represented file information with 16-bit integers, which were rapidly obsoleted by disk progress. People switched to a 32-bit file system, first using int[2] constructs which were not only awkward, but also not efficiently portable to 32-bit hardware.

To solve the problem, the long type was added to the language, even though this required C on the PDP-11 to generate multiple operations to simulate 32-bit arithmetic. Even as 32-bit minicomputers became available alongside 16-bit systems, people still used int for efficiency, reserving long for cases where larger integers were truly needed, since long was noticeably less efficient on 16-bit systems. Both short and long were added to C, making short available for 16 bits, long for 32 bits, and int as convenient for performance. There was no desire to lock the numbers 16 or 32 into the language, as there existed C compilers for at least 24- and 36-bit CPUs, but rather to provide names that could be used for 32 bits as needed.

PDP-11 C might have been re-implemented with int as 32-bits, thus avoiding the need forlong; but that would have made people change most uses of int to short or suffer serious performance degradation on PDP-11s. In addition to the potential impact on source code, the impact on existing object code and data files would have been worse, even in 1976. By the 1990s, with an immense installed base of software, and with widespread use of dynamic linked libraries, the impact of changing the size of a common data object in an existing environment is so high that few people would tolerate it, although it might be acceptable when creating a new environment. Hence, many vendors, to avoid namespace conflicts, have added a 64-bit integer to their 32-bit C environments using a new name, of which long long has been the most widely used.

关于c - Int 类型不应该是平台字长的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21501507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com