#023 – How big is an int?

In #021 – Thinking in memory. What a variable ACTUALLY is, we established that variables are simply representations of values that are stored in memory locations. When you initialize a variable int y {11};, the compiler reserves a portion of memory in bytes.

How this is done is abstracted from the programmer. We don’t need to be concerned with the details since we interact with the variable through its identifier, not through its address. (At least on a beginner level. Advanced C++ topics such as pointers deal directly with memory addresses).

The C++ standard does not mandate a fixed size for most fundamental types.

An int can be either a short, int, long, long long each occupying different space in memory, either 4 to 8 bytes (See the table below).

The size of an int not being mandated is for historical reasons. Back in the days of C (and history), computers were slow and performance was priority. C chose to be lax on the size of an int, letting the compiler define its size for performance.

C++ gives the compiler the freedom to optimize the program by not enforcing a size for variables. This flexibility allows C++ to remain performant across everything from embedded microcontrollers to 64-bit servers — but it also means the size of a type can vary from platform-to-platform.

TypeMinimum SizeTypical Size
char32_t4 bytes4 bytes
short2 bytes2 bytes
int2 bytes4 bytes
long4 bytes4 or 8 bytes
long long8 bytes8 bytes

If your code depends on a type being a specific size — for binary file formats, network protocols, or low-level bit manipulation — don’t let the compiler decide Use the fixed-width types from <cstdint> (std::int32_t, std::int64_t, etc.) when exact sizes is a priority

The sizeof() operator

To get some insight into how much memory our variables occupy, we can use the sizeof() operator.

Run the program below. You might get a different result based on your compiler, OS, computer architecture!

#include <iomanip> // for std::setw 
#include <iostream>

int main()
{
    std::cout << std::left; // Formatting

    std::cout << std::setw(16) << "short:" << sizeof(short) << " bytes\\n";
    std::cout << std::setw(16) << "int:" << sizeof(int) << " bytes\\n";
    std::cout << std::setw(16) << "long:" << sizeof(long) << " bytes\\n";
		
		float varX;		
		std::cout << std::setw(16) << "float: " << sizeof(varX) << " bytes\\n";
}

Here’s what I got

// Output
short:          2 bytes
int:            4 bytes
long:           8 bytes
float:          4 bytes

Ultimately

The beauty of C++ is that it is a high-level and low-level language SIMULTANEOUSLY. In this case, there was a requirement to remove the abstraction about memory allocation. C++ gives us the freedom to remove this ambiguity.

Leave a Reply

Your email address will not be published. Required fields are marked *