C Data Types: The Ultimate Beginner’s Guide
In C programming, data types define the type of data a variable can store. Choosing the right data type is essential for efficient memory use, program accuracy, and performance.
Let’s explore the built-in, derived, and user-defined data types in C with examples and tips.
Basic (Primary) Data Types
Data Type | Description | Size (Typical) | Example |
---|---|---|---|
int | Integer | 2 or 4 bytes | int age = 30; |
float | Single-precision float | 4 bytes | float pi = 3.14; |
double | Double-precision float | 8 bytes | double x = 10.9; |
char | Character | 1 byte | char grade = 'A'; |
Example Program:
#include <stdio.h>
int main() {
int age = 25;
float pi = 3.14;
double largeValue = 123456.789;
char initial = 'M';
printf("Age: %d\n", age);
printf("PI: %.2f\n", pi);
printf("Large Value: %.3lf\n", largeValue);
printf("Initial: %c\n", initial);
return 0;
}
Derived Data Types
These are based on the basic data types:
Type | Description | Example |
---|---|---|
Array | Collection of same type | int numbers[5]; |
Pointer | Address of a variable | int *ptr = &age; |
Function | Returns a specific type | int sum(int a, int b) |
User-defined Data Types
You can define your own types using:
Keyword | Use | Example |
---|---|---|
struct | Group different data types | struct Person { char name[50]; int age; }; |
union | Shared memory for members | union Data { int i; float f; }; |
enum | Named integer constants | enum Color { RED, GREEN, BLUE }; |
typedef | Create aliases for types | typedef int Marks; |
Size of Data Types (Platform Dependent)
Data Type | Size (32-bit system) |
---|---|
char | 1 byte |
int | 4 bytes |
float | 4 bytes |
double | 8 bytes |
Use sizeof()
to check data type size:
printf("%lu", sizeof(int));
Best Practices for Data Types
- Use
int
for counting,float/double
for real numbers - Use
char
for characters, not strings - Use the smallest data type that fits your needs
- Group related variables using
struct
- Prefer
enum
for readable constants
Common Mistakes to Avoid
Mistake | Why It’s a Problem |
---|---|
Using wrong data type | Can waste memory or cause errors |
Not checking type sizes | Leads to portability issues |
Mixing types without casting | May cause unexpected results |