Checking Type Sizes and Limits in C++ (sizeof, <limits>)
You’ve already met int, long, and long long, and you know their sizes can vary depending on platform and compiler. But “can vary” raises a question: how do you actually find out how big a type is on your machine? And once you know the size, how do you find out the largest or smallest value that fits inside it?
C++ gives you two tools for this: the sizeof operator, which tells you how many bytes a type takes up, and the <limits> header, which tells you the smallest and largest values a type can hold.
Number of bytes with sizeof
sizeof is a operator built into the language. You give it a type, or a variable, and it tells you how many bytes that thing takes up in memory.
On most computers, you’ll see the output 4, 8, 1, and 1. That means an int takes 4 bytes, a double takes 8, and a char or bool each take just 1.
You can also use sizeof directly on a variable, instead of a type name:
int playerScore = 9500;std::cout << sizeof(playerScore) << "\n"; // same answer as sizeof(int)Why isn’t the size always the same?
On almost every desktop or laptop computer today, int happens to be 4 bytes, but the language’s standard (its official definition) leaves room for other specialized computers, like small embedded chips found in microwaves or thermostats, to use a smaller int if that fits the hardware better. This is a deliberate design choice. Locking every type to one exact size everywhere would have made the language slower or impossible to use on some of that hardware.
The range of values with <limits>
Knowing a type’s size in bytes is useful, but it doesn’t directly tell you the range of values it can store. For that, C++ gives you a tool called std::numeric_limits, which belongs to a header called <limits>.
This prints the largest value an int can hold, followed by the smallest.
The syntax here looks a little unusual if you haven’t seen angle brackets <> used like this before. Think of the syntax std::numeric_limits<int> as asking a question: "tell me the limits, specifically for the int type."
You could just as easily ask about a different type:
The general pattern is std::numeric_limits<TYPE>::max() and std::numeric_limits<TYPE>::min().
A gotcha with floating-point minimums
There’s one surprising detail when applying min() to a double. For whole number types like int, min() gives you exactly what you’d expect: the most negative number possible.
But for double, min() gives you the smallest positive number the type can represent, a value very close to zero. If you want the most negative double, you need to write it as -std::numeric_limits<double>::max() instead.