User-defined data types in C allow programmers to create their own data types based on the existing basic and derived data types. These types help in organizing and structuring data in a way that is meaningful for the problem being solved. The primary user-defined data types in C are structures, unions, enumerations, and typedefs.
1. Structures:
- Structures allow users to define a composite data type that groups variables of different data types under a single name.
- Each variable inside the structure is called a member.
- Structs provide a way to represent complex entities with multiple attributes.
struct Person {
char name[50];
int age;
float height;
};
struct Person john; // Creating an instance of the structure
2. Unions:
- Unions are similar to structures but share the same memory location for all their members.
- Only one member of a union can be accessed at a time.
- Useful when different data types need to share the same memory space.
union Data {
int i;
float f;
char str[20];
};
union Data myData; // Creating an instance of the union3. Enumerations (Enums):
- Enums provide a way to create named integer constants.
- They offer a readable and symbolic representation for a set of related values.
- Enums make the code more self-documenting.
enum Color { RED, GREEN, BLUE };
enum Color selectedColor = GREEN;4. Typedef:
typedef
is used to create an alias for an existing data type.- It allows programmers to define custom names for existing data types, making the code more readable and portable.
typedef unsigned int uint; // uint is now an alias for unsigned
int uint x = 42;
These user-defined data types help improve code organization, readability, and maintainability. They allow programmers to model real-world entities more effectively and create abstractions that make code easier to understand and reason about.