We are going learn how C stores integers at a low level, with real examples. And see how different integer types work in memory and how they behave in code.
1. What is an Integer
An integer is a whole number (no fractions). Example(s):
5
,-10
,0
,1000
In C, integers come in different sizes:
Type | Size (bytes) | Range (signed) | Range (unsigned) |
---|---|---|---|
char |
1 | -128 to 127 | 0 to 255 |
short |
2 | -32,768 to 32,767 | 0 to 65,535 |
int |
4 | -2.1B to 2.1B (~) | 0 to 4.2B (~) |
long |
4 or 8 | Depends on system | Depends on system |
long long |
8 | -9.2Q to 9.2Q (~) | 0 to 18.4Q (~) |
2. Examples
Example 1: Basic Integer Types
#include <stdio.h>
int main() {
char a = 100; // 1-byte integer
short b = 20000; // 2-byte integer
int c = 1000000; // 4-byte integer
long long d = 5000000000; // 8-byte integer
printf("a = %d, b = %d, c = %d, d = %lld\n", a, b, c, d);
return 0;
}
Output:
a = 100, b = 20000, c = 1000000, d = 5000000000
Example 2: Signed vs Unsigned
#include <stdio.h>
int main() {
signed char x = -100; // Can be negative
unsigned char y = 200; // Only positive
printf("x = %d, y = %u\n", x, y);
return 0;
}
Output:
x = -100, y = 200
Example 3: Overflow (What happens when a number is too big)
#include <stdio.h>
int main() {
unsigned char z = 255; // Max value for unsigned char
z = z + 1; // Overflow!
printf("z = %u\n", z); // Wraps around to 0
return 0;
}
Output:
z = 0
3. How Integers Look in Memory (Binary & Hex)
Let’s see how int num = 255
is stored in memory:
- Binary:
00000000 00000000 00000000 11111111
- Hex:
00 00 00 FF
(Little-endian systems store it as FF 00 00 00
in memory!)
4. Takeaways
- Different integer types save memory and prevent overflow.
- Signed = negative & positive, Unsigned = only positive.
- If a number is too big, it “wraps around” (overflow).