If the integer value I want to store is only requiring 1 signed byte, should I use a char or a short for the variable type?
If the program was for a limited hardware system, I would obviously want to use a char for memory efficiency, but should I favour the potentially more readable short if the program is for a system with negligible effect? Or would it be considered common knowledge enough that a char represents a signed byte?
signed char
or int_least8_t
if you want at least 8 bits.int8_t
if you want exactly 8 bits.In C terms, char
, unsigned char
and signed char
are exactly one byte. But a byte is simply the smallest supported type. Historically, these types could be less than 8 bits in size, or as much as 32 bits. Nowadays, they are usually 8 bits in size, but they could (rarely) be larger. CHAR_BIT
is the size of these types in bits.
I think you actually want an octet, which is to say an 8-bit type. For that, you can use int8_t
and uint8_t
from stdint.h
. These are guaranteed to be exactly 8 bits in size. If the environment doesn't support these, the types won't be provided and you'll get a compile-time error.
There's also int_least8_t
and uint_least8_t
from stdint.h
. These will be the smallest type available that's at least 8 bits in size.
Notably, you shouldn't use char
since it's up the implementation whether char
is signed or unsigned, and different implementations make different choices.