为什么数据类型的大小会随着操作系统的变化而变化? [英] Why do the sizes of data types change as the Operating System changes?

查看:183
本文介绍了为什么数据类型的大小会随着操作系统的变化而变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是在采访中问我的,在某些操作系统中,char的大小是2个字节,但是在某些操作系统中,它是4个字节或不同.

This question was asked to me in an interview, that size of char is 2 bytes in some OS, but in some operating system it is 4 bytes or different.

为什么会这样?

为什么它与其他基本类型(例如int)不同?

Why is it different from other fundamental types, such as int?

推荐答案

这可能是一个技巧问题. sizeof(char)总是 1.

That was probably a trick question. The sizeof(char) is always 1.

如果大小不同,则可能是由于编译器不合格,在这种情况下,问题应该是关于编译器本身,而不是C或C ++语言.

If the size differs, it's probably because of a non-conforming compiler, in which case the question should be about the compiler itself, not about the C or C++ language.

1 sizeof运算符产生对象中的字节数 其操作数的表示形式.操作数可以是一个表达式, 未评估的值,或带括号的type-id.的大小 运算符不得应用于具有功能或 不完整类型,或在所有其枚举数之前变为枚举类型 已经声明过,或者是此类类型的括号名称,或者是 指定位字段的左值. sizeof(char)sizeof(signed char)sizeof(unsigned char)为1.应用于任何其他基本类型(3.9.1)的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位表示的效率更高.

The sizeof of other types than the ones pointed out are implementation-defined, and they vary for various reasons. An int has better range if it's represented in 64 bits instead of 32, but it's also more efficient as 32 bits on a 32-bit architecture.

这篇关于为什么数据类型的大小会随着操作系统的变化而变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆