問題描述
整數(shù)的大小是否取決于編譯器、操作系統(tǒng)和處理器?
Would the size of an integer depend upon the compiler, OS and processor?
推薦答案
這個(gè)問題的答案取決于我們愿意得到的實(shí)際考慮有多遠(yuǎn).
The answer to this question depends on how far from practical considerations we are willing to get.
最終,理論上,C 和 C++ 中的一切都依賴于編譯器,并且只依賴于編譯器.硬件/操作系統(tǒng)根本不重要.編譯器可以自由地實(shí)現(xiàn)任何厚度的硬件抽象層,并且可以完全模擬任何東西.沒有什么可以阻止 C 或 C++ 實(shí)現(xiàn)實(shí)現(xiàn)任何大小和任何表示的 int
類型,只要它足夠大以滿足語言標(biāo)準(zhǔn)中指定的最低要求.這種抽象級別的實(shí)際示例很容易獲得,例如基于虛擬機(jī)"平臺的編程語言,如 Java.
Ultimately, in theory, everything in C and C++ depends on the compiler and only on the compiler. Hardware/OS is of no importance at all. The compiler is free to implement a hardware abstraction layer of any thickness and emulate absolutely anything. There's nothing to prevent a C or C++ implementation from implementing the int
type of any size and with any representation, as long as it is large enough to meet the minimum requirements specified in the language standard. Practical examples of such level of abstraction are readily available, e.g. programming languages based on "virtual machine" platform, like Java.
然而,C 和 C++ 旨在成為高度高效的語言.為了實(shí)現(xiàn)最高效率,C 或 C++ 實(shí)現(xiàn)必須考慮源自底層硬件的某些考慮因素.出于這個(gè)原因,確保每個(gè)基本類型都基于硬件直接(或幾乎直接)支持的某種表示很有意義.從這個(gè)意義上說,基本類型的大小確實(shí)取決于硬件.
However, C and C++ are intended to be highly efficient languages. In order to achieve maximum efficiency a C or C++ implementation has to take into account certain considerations derived from the underlying hardware. For that reason it makes a lot of sense to make sure that each basic type is based on some representation directly (or almost directly) supported by the hardware. In that sense, the size of basic types do depend on the hardware.
換句話說,64 位硬件/OS 平臺的特定 C 或 C++ 實(shí)現(xiàn)完全可以自由地將 int
實(shí)現(xiàn)為占用 128 位的 71 位 1 的補(bǔ)碼整數(shù)類型內(nèi)存,使用其他 57 位作為填充位,這些位總是需要存儲編譯器作者的女朋友的生日.這種實(shí)現(xiàn)甚至?xí)哂幸欢ǖ膶?shí)用價(jià)值:它可以用于執(zhí)行 C/C++ 程序可移植性的運(yùn)行時(shí)測試.但這就是該實(shí)現(xiàn)的實(shí)際用途將結(jié)束的地方.不要期望在普通"的 C/C++ 編譯器中看到類似的東西.
In other words, a specific C or C++ implementation for a 64-bit hardware/OS platform is absolutely free to implement int
as a 71-bit 1's-complement signed integral type that occupies 128 bits of memory, using the other 57 bits as padding bits that are always required to store the birthdate of the compiler author's girlfriend. This implementation will even have certain practical value: it can be used to perform run-time tests of the portability of C/C++ programs. But that's where the practical usefulness of that implementation would end. Don't expect to see something like that in a "normal" C/C++ compiler.
這篇關(guān)于int 的大小是否取決于編譯器和/或處理器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!