Range of Numeric Types in C++ - dummies

Range of Numeric Types in C++

By Stephen R. Davis

It may seem odd, but the C++ standard doesn’t say exactly how big a number each of the data types can accommodate. The standard speaks only to the relative size of each data type. For example, it says that the maximum long int is at least as large as the maximum int.

The authors of C++ weren’t trying to be mysterious. They merely wanted to allow the compiler to implement the absolute fastest code possible for the base machine. The standard was designed to work for all different types of processors running different operating systems.

However, it is useful to know the limits for your particular implementation. The table shows the size of each number type on a Windows PC using the Code::Blocks/gcc compiler.

Range of Numeric Types in Code::Block/gcc
Variable Size (bytes) Accuracy Range
short 2 exact -32768 to 32767
int 4 exact 2,147,483,648 to 2,147,483,647
long 4 exact -2,147,483,648 to 2,147,483,647
long long int 8 exact -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 7 digits ±3.4028 x 10±38
long 8 16 digits ±1.7977 x 10±308
long double 12 19 digits ±1.1897 x 10±4932

Attempting to calculate a number that’s beyond the range of its type is known as an overflow. The C++ standard generally leaves the results of an overflow as undefined. That’s another way that the definers of C++ remained flexible.

On the PC, a floating-point overflow results in an exception, which if not handled will cause your program to crash. As bad as that sounds, an integer overflow is worse — C++ silently generates an incorrect value without complaint.