Should I use cstdint?

ronag picture ronag · May 26, 2011 · Viewed 13.2k times · Source

I have been pondering on whether or not I should use the typedefs inside <cstdint> or not.

I personally prefer writing uint32_t over unsigned int and int8_t over char etc... since it to me is alot more intuitive.

What do you guys think? Is it a good idea to use the typedefs from <cstdint> or not? Are there any disadvantages?

Answer

Nemo picture Nemo · May 26, 2011

Actually, I would suggest using both.

If you want something that is definitely 32-bits unsigned, use uint32_t. For example, if you are implementing a "struct" to represent an external object whose specification defines one of its fields as 32 bits unsigned.

If you want something that is the "natural word size of the machine", use int or unsigned int. For example:

for (int i = 0 ; i < 200 ; ++i)
    // stuff

The "natural word size of the machine" is going to give you the best performance, both on today's processors and on tomorrow's.

Use "char" if you mean "character"; "char" or "unsigned char" if you mean "byte". C/C++ lets you access an arbitrary object's bytes via "char *", not anything else, strictly speaking.

Use uint8_t or int8_t if you specifically want an 8-bit integer, similar to uint32_t.