简体   繁体   中英

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 .

And the guy is using datatype int . And that is the tricky part. Int can be 2, 4, 8 or maybe in the future 16 Bytes.

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. Hence the word "stretching".

This should make software safer. But for this requirement, there are other measures. For safe software, nobody would use int . There are for example the MISRA rules that require, not to use any build in data type. And you can use types. That's anyway better.

So "stretching" means: Same value for stretched (bigger) variable types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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