Ph.D. in Computer Science at Rutgers University

Integral and Float type in C

In this article, I'll make a overview on integral types and variables in C. (If you're qutie familiar with C programming, you can skip this article:) Let's go over the size and range of integral and float types in C.

/* test.c */
#include <stdio.h>

int main() {
	// print size of basic types
	printf("size of short = %d\n", sizeof(short));
	printf("size of unsigned short = %d\n", sizeof(unsigned short));
	printf("size of int = %d\n", sizeof(int));
	printf("size of unsigned int = %d\n", sizeof(unsigned int));
	printf("size of long = %d\n", sizeof(long));
	printf("size of unsigned long = %d\n", sizeof(unsigned long));
	printf("size of long long = %d\n", sizeof(long long));
	printf("size of unsigned long long = %d\n", sizeof(unsigned long long));
	printf("size of float = %d\n", sizeof(float));
	printf("size of double = %d\n", sizeof(double));
	printf("size of long double = %d\n", sizeof(long double));
	return 0;

Let's compile this program in GCC:

gcc -o test test.c

Now the result of those codes are: (on x86_64 Linux)

size of short = 2
size of unsigned short = 2
size of int = 4
size of unsigned int = 4
size of long = 8
size of unsigned long = 8
size of long long = 8
size of unsigned long long = 8
size of float = 4
size of double = 8
size of long double = 16

Size and range of integral and float types may differ in different platforms, even different compilers. Thus, it's recommended to know the varaiable sizes in your environment.
The range of integral types are qutie easy to calculate:

Type Size Ranges
short 2 byte [-215, 215-1]
unsigned short 2 byte [0, 216-1]
int 4 byte [-231, 231-1]
unsigned int 4 byte [0, 232-1]
Type Size Ranges
long 8 byte [-263, 263-1]
unsigned long 8 byte [0, 264-1]
long long 8 byte [-263, 263-1]
unsigned long long 8 byte [0, 264-1]

How does the range of float types? How are they formed in computer? How accurate do float types support? Now let's take a look at how the computer stores the float types. Inside most modern computer, numbers are stored in the form of two's complement. If you're interested in how and why we need two's complement, click here.

Looking at float type whose size is 4 bytes, the picture above shows how the data is stored (value = M*2E). And there's an example of how to calculate a float number given in binary. Thus, we could easily calculate the range of float and double type:

The range of float type is [-2*227-1, 2*227-1], that is [-2128, 2128], same to [-3.40E38, 3.40E38]

The range of double type is [-2*2210-1, 2*2210-1], that is [-21024, 21024], same to [-1.79E308, 1.79E308]

Now let's look at the accuracy that float and double could support:

For float, 223 = 8388608, that means float could support 6 to 7 significant digits after decimal.
For double, 252 = 4503599627370496, that means double could support 15 to 16 significant digits after decimal.