can somebody explain me what the advantage of small data types like char
(8-Bit) or short
(16-Bit) compared to int
(32-Bit) (esp. in C/C++).
In my mind it does not bring any advantage esp. on a 32-Bit machine, because of its word size is always 32-Bit. Is it a compiler thing, that in some cases some small types can be combined in one register, to save memory? So are small data types just intended for hardware architectures lower than 32-Bit or/and with little memory?
Additi开发者_运维技巧onal I see a new target for failures by overflowing the data type, so I hink it shouldn't be lightly used...
Even if the machine has a word size of 32 bit, doesn't mean that all the data types are stored in word boundary, or even that the minimum unit of information storage is the word. Say that you have to create a vector of a thousand characters. If you create it like this:
std::vector<char> v(1000);
it will use around a thousand bytes (usually). If you assume that the minimum storage unit is the word, you could declare it instead like this (thinking that anyway each char will use a 32 bit word):
std::vector<int> v(1000);
but this will give you around 4 bytes * 1000, which is four times the previous declaration.
That is, sometimes, and depending on how you declare your types, they get packed, so they don't use a word for storing each piece of information. In the first case, the compiler/implementaiton of vector<char>
will create a buffer of 1000 bytes to store all the chars packed.
So, the answer would be that the advantage is saving memory space.
精彩评论