Real-Life Examples of Data Types
Why Real-Life Examples Matter
Data types in C are not just abstract concepts; they directly map to real-world scenarios.
Choosing the right data type ensures your program behaves correctly and uses memory efficiently.
Examples in Context
1. **Banking**: Prefer storing money in **integer cents** (e.g., `long long cents = 152375;`) to avoid floating-point rounding; if you must display, convert to dollars at print time.
2. **Gaming**: An `int` for player score, a `float` for character speed, and a `char` for rank (e.g., 'A').
3. **Weather Applications**: A `double` for temperature (higher precision), an `int` for day count, and a `char[]` for city name.
4. **School System**: An `int` for student ID, a `char` for grade, and a `char[]` for student name.
#include <stdio.h>
int main(void) {
int studentID = 1234; // integer ID
char grade = 'B'; // single-character grade
long long balanceCents = 105075; // $1050.75 stored as integer cents
char name[] = "Alice"; // C string (char array, null-terminated)
// Print money by formatting integer cents
printf("ID: %d, Name: %s, Grade: %c, Balance: %lld.%02lld\n",
studentID, name, grade,
balanceCents / 100, balanceCents % 100);
return 0;
}
ID: 1234, Name: Alice, Grade: B, Balance: 1050.75
Strings in C (char arrays)
C has no built-in `string` type; text is stored as an array of `char` terminated by a null byte (`'\0'`).
Use safe I/O like `fgets` and safe formatting like `snprintf` to avoid buffer overflows.
Analogies
• **int** → like a counter in a store keeping track of how many items are sold.
• **float/double** → like a thermometer showing a precise temperature.
• **char** → like a single symbol on a keyboard.
• **char array (C string)** → like a person’s name tag containing letters.
Combining Types with struct
`struct` lets you group different data types into one real-world entity.
#include <stdio.h>
struct Student {
int id;
char name[32];
char grade; // e.g., 'A', 'B', ...
long long balance; // cents
};
int main(void) {
struct Student s = {1234, "Alice", 'B', 105075};
printf("%d,%s,%c,%lld.%02lld\n",
s.id, s.name, s.grade, s.balance/100, s.balance%100);
return 0;
}
Best Practices
• Match the data type to the real-world property (e.g., use an integer for an age or a count).
• Avoid `float`/`double` for **money**; prefer integer cents or fixed-point. Use `double` for measurements (science/engineering).
• Use `char` for single-character flags/grades and `char[]` (strings) for names or addresses.
• Consider `struct` to model real-world entities composed of multiple fields.