Lesson 5 of 7 · C Foundations · 4 min read · Updated
Data type sizes and ranges
short, int, long, long long and unsigned: how big each is, the largest value it can hold, and what happens past it.
Every C variable has a fixed size in memory, and that size decides the range of values it can hold. Pick a type too small and a big number simply does not fit. sizeof tells you the size in bytes, and limits.h gives the exact limits.
#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("char: %zu byte, %d to %d\n", sizeof(char), CHAR_MIN, CHAR_MAX);
printf("short: %zu bytes, %d to %d\n", sizeof(short), SHRT_MIN, SHRT_MAX);
printf("int: %zu bytes, %d to %d\n", sizeof(int), INT_MIN, INT_MAX);
printf("long long: %zu bytes, %lld to %lld\n", sizeof(long long), LLONG_MIN, LLONG_MAX);
printf("unsigned int: 0 to %u\n", UINT_MAX);
return 0;
}
char: 1 byte, -128 to 127
short: 2 bytes, -32768 to 32767
int: 4 bytes, -2147483648 to 2147483647
long long: 8 bytes, -9223372036854775808 to 9223372036854775807
unsigned int: 0 to 4294967295
The integer types and how to print them
short(%hd) — 2 bytes, about ±32 thousand. Rarely needed today.int(%d) — 4 bytes, about ±2.1 billion. The everyday choice.longorlong int(%ld) — at least 4 bytes: 4 on Windows, 8 on Linux and Mac.long long(%lld) — 8 bytes, about ±9.2 × 1018. Use it for really large whole numbers.unsignedversions (%u,%lu,%llu) — no negatives, so the top of the range doubles.
#include <stdio.h>
int main(void)
{
long population = 1400000000L; /* L marks a long constant */
long long savings = 50000000000LL; /* 500 crore paise: too big for int */
unsigned int count = 4000000000U; /* fits only because it is unsigned */
printf("%ld\n", population);
printf("%lld\n", savings);
printf("%u\n", count);
return 0;
}
1400000000
50000000000
4000000000
Warning
Going past a type's limit is called overflow. For unsigned types the value wraps round to 0; for signed types like int the C standard says the result is undefined — anything may happen. When a total might pass about two billion, use long long from the start.
Note
Decimal types have ranges too: float keeps about 7 significant digits, double about 15, and long double at least as many as double. Sizes can differ between computers, which is why sizeof exists — never assume, measure.
Which type should hold a bank total of 5,000,000,000 (five billion) paise?
Try this now
- Run the first program on your computer. Is
long4 or 8 bytes there? Add a line withsizeof(long)to find out. - Print
sizeof(float),sizeof(double)andsizeof(long double). - Work out 20 factorial with
int, then withlong long, and compare the answers.
Create a free account to save your progress, or sign in.