In C, data types specify the type of data that variables can hold. Understanding data types is crucial for declaring variables and performing operations on data. Here's an overview of C data types with examples:
1. Basic Data Types:
a. int:
- Used to store integers (whole numbers).
- The size of int
can vary depending on the system (e.g., 2 or 4 bytes).
int age = 30; // Declaration and initialization of an int variable
b. float:
- Represents single-precision floating-point numbers (numbers with decimal points).
- Typically 4 bytes in size.
float price = 12.99; // Declaration and initialization of a float variable
c. double:
- Represents double-precision floating-point numbers (more precise than float
).
- Typically 8 bytes in size.
double pi = 3.14159265359; // Declaration and initialization of a double variable
d. char:
- Used for single characters.
- 1 byte in size, typically.
char grade = 'A'; // Declaration and initialization of a char variable
e. _Bool (C99 and later):
- Represents boolean values.
- Can have two values: 0
for false and 1
for true.
_Bool isStudent = 1; // Declaration and initialization of a boolean variable
2. Modifiers:
a. short:
- Reduces the size of an int
.
- A short int
is typically 2 bytes.
short int temperature = 25; // Declaration and initialization of a short integer variable
b. long:
- Extends the size of an int
.
- A long int
is typically 4 bytes.
long int population = 1000000; // Declaration and initialization of a long integer variable
3. Derived Data Types:
a. Arrays:
- A collection of elements of the same data type.
- Elements are accessed by their index.
int numbers[5] = {1, 2, 3, 4, 5}; // Declaration and initialization of an integer array
b. Pointers:
- Variables that store memory addresses.
- Used for dynamic memory allocation and creating data structures.
int x = 42; // Declaration and initialization of an integer variable
int* ptr = &x; // Declaration and initialization of an integer pointer
c. Structures:
- User-defined data types that group variables of different data types together.
struct Person {
char name[50];
int age;
};
struct Person john; // Declaration of a structure variable
john.age = 30; // Assigning values to structure members
d. Unions:
- Similar to structures but only one of the variables can have a value at a time, sharing the same memory location.
union Value {
int x;
float y;
};
union Value data; // Declaration of a union variable
data.x = 42; // Assigning a value to one member of the union
e. Enums (Enumerated Types):