Archive for March, 2010

Guarantees in sizes of C++ objects

Monday, March 29th, 2010

Well, this is really basic, but something I did not always remember. So I decided to check up on this in Stroustrup book that happened to be on my table this morning. Here is what I found:

C++ objects are expressed in terms of multiples of the size of a char, so by definition the size of a char is 1. Here is the guarantee provided by the language:

1 ≡ sizeof(char) ≤ sizeof(short) ≤ sizeof(int) ≤ sizeof(long)
1 ≤ sizeof(bool) ≤ sizeof(long)
sizeof(char) ≤ sizeof(wchar_t) ≤ sizeof(long)
sizeof(float) ≤ sizeof(double) ≤ sizeof(long double)
sizeof(N) ≡ sizeof(signed N) ≡ sizeof(unsigned N)

where N can be char, short int, int, or long int. It is also guaranteed that a char has at least 8 bits, a short and an int at least 16 bits, a long at least 32 bits. A char can hold a character of the machine’s character set.

Certainly interesting that I don’t remember half of this. Some of them are what we already know from basic computer organization class (where some of us learned C), but my memory doesn’t last that long.

P.S. This is also certainly very different from Java, where the basic “1″ is actually an int instead of a char.