What Are Variables?
A variable is a named storage location in memory that holds a value. In C, every variable must be declared with a type before it can be used. The type tells the compiler how much memory to allocate and how to interpret the bits stored there.
c
Important: C is a statically-typed language. Once you declare a variable asint, it stays anintforever. There is no runtime type flexibility like Python or JavaScript.
Fundamental Data Types
Integer Types
| Type | Size (typical) | Range |
|---|---|---|
char | 1 byte | -128 to 127 |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 4 or 8 bytes | Platform-dependent |
long long | 8 bytes | ±9.2 × 10¹⁸ |
c
Floating-Point Types
| Type | Size | Precision |
|---|---|---|
float | 4 bytes | ~7 decimal digits |
double | 8 bytes | ~15 decimal digits |
long double | 12–16 bytes | ~18–33 decimal digits |
c
Pitfall: Never compare floating-point numbers with==. Due to precision limits,0.1 + 0.2does not equal0.3exactly. Use a tolerance threshold instead.
c
The char Type
char is technically an integer type that stores ASCII values. This duality is fundamental to understanding C strings.c
Type Modifiers
signed vs unsigned
By default, integer types are
signed (can hold negative values). The unsigned modifier shifts the range to non-negative values only, effectively doubling the positive range.c
const — Immutable Variables
c
The sizeof Operator
sizeof returns the size of a type or variable in bytes. It's evaluated at compile time, not runtime.c
Tip: Always usesizeofinstead of hardcoding sizes. Sizes can differ between platforms (32-bit vs 64-bit), sosizeof(int)is more portable than writing4.
Type Conversion
Implicit (Automatic) Conversion
C automatically converts types in expressions following a promotion hierarchy:
char → short → int → long → float → double.c
Explicit Casting
c
Fixed-Width Integer Types (C99+)
For portable code, use the exact-width types from
<stdint.h>:c
These guarantee exact sizes across all platforms — critical for network protocols, file formats, and embedded systems.
Boolean Type (C99+)
C99 introduced
<stdbool.h> for boolean values:c
Note: Before C99, C had no boolean type. Programmers usedintwith0for false and non-zero for true. This convention still appears in legacy code.
Summary
| Concept | Key Point |
|---|---|
| Declaration | Every variable needs a type: int x = 5; |
| Integer types | char < short < int < long < long long |
| Float types | float (7 digits) < double (15 digits) |
unsigned | Doubles positive range, no negatives |
sizeof | Returns size in bytes at compile time |
| Casting | (double)x forces type conversion |
| Fixed-width | Use <stdint.h> for portable exact sizes |