C Data Types
What Are Data Types?
A data type defines the kind of data a variable can store, such as numbers, characters, or decimals. In C, data types also specify the size in memory and the range of values a variable can hold.
Type sizes and ranges are implementation-defined (they can vary by compiler/architecture). Choosing the correct data type is essential for correctness and efficiency—for example, storing age as an `int` makes sense, while using a `float` would be unnecessary and less precise for whole-number ages.
Categories of Data Types
C divides data types into several categories:
1. **Basic (Fundamental) types** → `int`, `char`, `float`, `double`
2. **Derived types** → arrays, pointers, **structures**, **unions**, and **function types**
3. **Enumeration types** → `enum`, representing a set of named integer constants
4. **Type aliases** → created with `typedef` to improve readability (aliases don’t create new distinct types)
Category | Examples | Description |
---|---|---|
Basic types | int, float, char, double | Directly supported by the language |
Derived types | array, pointer, struct, union, function | Built from basic types |
Enumeration | enum Color { RED, GREEN, BLUE }; | User-defined set of named integer constants |
Type alias | typedef unsigned int Age; | `typedef` creates an alias (not a new distinct type) |
Signed vs Unsigned
Most integer types can be **signed** (default, can hold negative and positive values) or **unsigned** (only zero or positive values, with a larger positive range).
`char` without a qualifier may be either signed or unsigned depending on the implementation.
Example: `signed int x = -10; unsigned int y = 300;`
Boolean Type
C99 introduced the Boolean type via `_Bool` and the header `
Use `#include
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool ready = true;
if (ready) printf("Ready!\n");
return 0;
}
Ready!
Practical Example
Choosing the correct data type saves memory and prevents bugs. For example:
- Use `int` for counting items (whole numbers).
- Use `double` (or `float`) for measurements like height or distance.
- Use `char` for storing a single symbol like a grade ('A').
#include <stdio.h>
int main(void) {
int age = 25;
float height = 1.82f; // meters (float literal uses 'f')
char grade = 'A';
printf("Age: %d, Height: %.2f, Grade: %c\n", age, height, grade);
return 0;
}
Age: 25, Height: 1.82, Grade: A
Best Practices
• Prefer `int` for general-purpose integers unless you specifically need a wider/narrower range.
• Use `unsigned` only when negative values are impossible and be cautious mixing signed and unsigned (comparisons can surprise).
• Prefer `double` over `float` when precision matters (scientific calculations).
• Use `size_t` for sizes/array indices returned by `sizeof` or standard library functions.
• Use `typedef` and `enum` to improve readability (remember `typedef` is an alias, not a new distinct type).