gpt4 book ai didi

c++ - 为什么数据类型的大小会随着操作系统的变化而变化?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:04 25 4
gpt4 key购买 nike

这个问题是在面试中被问到的,char 的大小在某些操作系统中是 2 个字节,但在某些操作系统中是 4 个字节或不同。

为什么会这样?

为什么它不同于其他基本类型,例如 int

最佳答案

这可能是个棘手的问题。 sizeof(char) 总是 1。

如果大小不同,可能是因为编译器不一致,在这种情况下,问题应该与编译器本身有关,而不是与 C 或 C++ 语言有关。

5.3.3 Sizeof [expr.sizeof]

1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, or to an enumeration type before all its enumerators have been declared, or to the parenthesized name of such types, or to an lvalue that designates a bit-field. sizeof(char), sizeof(signed
char)
and sizeof(unsigned char) are 1. The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined.
(emphasis mine)

除上述类型外,其他类型的 sizeof 是实现定义的,并且由于各种原因而有所不同。如果 int 以 64 位而不是 32 位表示,则它的范围更广,但它在 32 位架构上作为 32 位也更高效。

关于c++ - 为什么数据类型的大小会随着操作系统的变化而变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12673735/

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