编译器是否隐式转换 int 类型
如果一个值设置为 int 例如 2,编译器是否将 int 类型转换为它需要的大小,例如 int8_t 或 uint16_t 等?
If a value is set to an int e.g. 2, does the compiler convert the int types to the size it needs e.g. int8_t or uint16_t etc.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
香草 C 中不存在,不。如果您不告诉编译器,它就不可能知道您的意思。
Not in vanilla C, no. The compiler can't possible know what you meant if you do not tell it.
如果你写的
话,默认类型是
signed int
。编译器的操作实际上取决于平台,但它必须保证int
的大小不小于short int
的大小且不大于长整型
'.sIf you write
the type is, by default,
signed int
. What the compiler does then really depends from the platform, but it has to guarantee thatint
's size is not less thanshort int
's and not greater thanlong int
'.s对于常量来说,这可能是正确的,通常也会进行小到大的反向转换:例如字节到 int。
它在某种程度上取决于编译器使用的实现和优化技术以及体系结构/操作系统的数据对齐要求。看看这篇写的。
For constants it may true, often the reverse conversion small to large is also done: byte to int for example.
It's somewhat dependent on the implementation and optimization techniques used by the compiler and the data alignment requirements by the architecture/OS. Have a look at this write up.
编译器首先查看表达式的上下文,了解它期望的类型。上下文可以是即
然后计算表达式,根据需要插入隐式类型转换(类型强制)。它进行
在所有位都很重要的情况下,您需要非常小心所编写的内容:类型、运算符和顺序。
The compiler first looks at the context of the expression, learning about what type it expects. The context can be i.e.
It then evaluates the expression, inserting implicit type conversions as needed (type coercion). It does
In situations where all the bits matter, you need to be extremely carefull about what you write: Types, operators and order.
整数是“int”类型的值。当使用运算符“=”将整数值分配给short 或char 时,int 值将转换为short 或char。编译器可能会检测到此转换并进行优化以在编译时转换整数值。
int8_t 和 uint16_t 不是标准类型。很多时候,这些类型可以定义为:
Integer numbers are values of the type "int". When you assign an integer value to short or char using the operator "=", the int value will be converted to short or char. The compiler may detect this conversion and do optimization to convert the integer value on compile time.
int8_t and uint16_t are not standard types. Many times these types may be defined as something like: