Normally I imagine most people would use int
for everything and ocassionally they would use unsigned int
when needed. Every now and then you might use a short int
, maybe for network traffic or something.
But lately I have started to use std::size_t
for indexing into STL containers (as I should), and then I started to find a use for std::uint8_t
when creating a struct of four 8-bit colour values (RGBA), rather than a char
, simply because it makes more sense to me (it's a number, not a character type, and not a 8-bit value, it's a 8-bit number from 0-255).
Then while doing some network programming I found that I wanted to make sure certain values being passed were 16-bits. And according to https://en.cppreference.com/w/cpp/language/types I can't assume a short int
is 16 bits, only that it's at least 16 bits. So I found a use for std::int16_t
.
This led me to gradually start using a fixed-width type everywhere. Which caused me to really think about what I needed, how much range I needed etc, whether it would fall into negative values or not.
So now, I have almost zero occurences of int
in my code.
There's three reasons in my head for this:
But I'm concerned that this is reducing performance as your usual consumer-grade CPU would operate on a native width type like a std::int32_t
better.
So, when should I use the fixed-width types, and how do they impact performance?
The fixed-width integer types that <inttypes. h> provides, include signed integer types, such as int8_t, int16_t, int32_t, int64_t, and unsigned integer types, such as uint8_t, uint16_t, uint32_t, and uint64_t.
uint64_t: unsigned 64-bit.
You should use int
when writing portable code (unless the integer size is constrained by external factors (e.g. protocol parsing), because this will allow machines to use the integer size that is preferred (optimal) on that machine.
There are a number of microprocessors in use whose register size is 16 bits for example; the compiler headers they provide set sizeof(int)
to 2. Using e.g. int32_t
on these machines for arithmetic would generate a lot of extra instructions.
However: For indexing, using int
is a bad idea: size_t
is preferable, even if you're guaranteed not to overflow the index by using int. This is because the value may need to be converted to the index register size (e.g. 64 bits for size_t
vs 32 bits for int
). This can be costly in inner loops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With