简体   繁体   English

MISRA-C:强制转换文字数字

[英]MISRA-C: cast literal number

I read a source code, there is a statement like: uint32 XYZ; 我阅读了源代码,其中有一条语句:uint32 XYZ; ... XYZ = (uint32)0x0000000U. ... XYZ =(uint32)0x0000000U。

I wonder if the cast is necessary, is XYZ = 0U OK? 我想知道是否需要强制转换,XYZ = 0U是否可以?

Thanks 谢谢

The integer constant 0U can in theory be an unsigned int of 64 bits. 理论上,整数常数0U可以是64位的无符号整数。 If so, the cast is necessary since MISRA-C (2012 10.3) does not allow implicit conversion to a narrower type. 如果是这样,由于MISRA-C(2012 10.3)不允许隐式转换为较窄的类型,因此必须进行强制转换。 However, the cast isn't necessary on 32 bit CPUs and smaller. 但是,在32位及以下的CPU上不需要强制转换。

An alternative is to write uint32_t XYZ = UINT32_C(0); 另一种方法是写uint32_t XYZ = UINT32_C(0); in which case the compiler picks the appropriate type for the integer constant automatically. 在这种情况下,编译器会自动为整数常量选择适当的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM