Variable Size in C++ - dummies

By Stephen R. Davis

In C++, memory is measured in bytes or bits. The keyword sizeof returns the size of its argument in bytes. The following program uses this to determine the size of the different variable types:

// VariableSize - output the size of each type of variable
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    bool        b; char  c; int    n; long         l;
    long long  ll; float f; double d; long double ld;
    cout << "sizeof a bool        = " << sizeof b << endl;
    cout << "sizeof a char        = " << sizeof c << endl;
    cout << "sizeof an int        = " << sizeof n << endl;
    cout << "sizeof a long        = " << sizeof l << endl;
    cout << "sizeof a long long   = " << sizeof ll<< endl;
    cout << "sizeof a float       = " << sizeof f << endl;
    cout << "sizeof a double      = " << sizeof d << endl;
    cout << "sizeof a long double = " << sizeof ld<< endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    cin.get();
    return 0;
}
The VariableSize program generates the following output:
sizeof a bool        = 1
sizeof a char        = 1
sizeof an int        = 4
sizeof a long        = 4
sizeof a long long   = 8
sizeof a float       = 4
sizeof a double      = 8
sizeof a long double = 12
Press Enter to continue...

As they say, “Your results may vary.” You may get different results if using a compiler other than gcc for Windows. For example, you may find that an int is smaller than a long.

C++ doesn’t say exactly how big a variable type must be; it just says that a long is the same size as or larger than an int and that a double is the same size as or larger than a float. The sizes shown here are typical for a 32-bit 80-x-86 processor.