简体   繁体   English

可伸展的常数

[英]Stretchable constants

This guideline talks about stretchable constants : 本指南讨论了可伸展的常量

Use "stretchable" constants whenever possible 尽可能使用“可伸缩”常量

Stretchable constants avoid problems with word-size variations. 可伸缩常数避免了字大小变化的问题。

It also provides an example: 它还提供了一个例子:

const int all_ones = ~0;
const int last_3_bits = ~0x7;

What are stretchable constants ? 什么是可伸展的常数

This is an old recommendation. 这是一个老建议。 You can recognize this also because the text is using const and not constexpr . 您也可以识别这一点,因为文本使用的是const而不是constexpr

And the guy is using datatype int . 那家伙正在使用数据类型int And that is the tricky part. 这是棘手的部分。 Int can be 2, 4, 8 or maybe in the future 16 Bytes. Int可以是2,4,8或者将来可能是16字节。

Stretchable means, you have a small (or whatever data type) and the assigned value will be the same, regardless of the implementation of the data type. 可伸缩意味着,您有一个小的(或任何数据类型),并且分配的值将是相同的,无论数据类型的实现如何。 If you want to have all bits set, and you will use ~0 , then this will work with an 8 bit or 16 bit or 32 bit or 64 bit value. 如果要设置所有位,并使用~0 ,则可以使用8位或16位或32位或64位值。 Hence the word "stretching". 因此,“拉伸”这个词。

This should make software safer. 这应该使软件更安全。 But for this requirement, there are other measures. 但是对于这个要求,还有其他措施。 For safe software, nobody would use int . 对于安全的软件,没有人会使用int There are for example the MISRA rules that require, not to use any build in data type. 例如,MISRA规则要求不使用任何数据类型的构建。 And you can use types. 你可以使用类型。 That's anyway better. 无论如何,这更好。

So "stretching" means: Same value for stretched (bigger) variable types. 所以“拉伸”意味着:拉伸(更大)变量类型的值相同。

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

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