Show List

Structures and Unions

In C, structures and unions are composite data types that allow you to group together variables of different data types.

A structure is a user-defined data type that groups together variables of different data types under a single name. The general syntax for declaring a structure in C is:

go
Copy code
struct structure_name { data_type1 variable1; data_type2 variable2; ... };

For example, the following code declares a structure named student that holds information about a student:

c
Copy code
struct student { int roll_no; char name[100]; float marks; };

You can create variables of a structure type using the structure name and access its members using the dot operator (.).

For example, the following code creates a variable of type student named s and accesses its members:

c
Copy code
#include <stdio.h> struct student { int roll_no; char name[100]; float marks; }; int main() { struct student s; s.roll_no = 123; strcpy(s.name, "John Doe"); s.marks = 85.5; printf("Roll No: %d\n", s.roll_no); printf("Name: %s\n", s.name); printf("Marks: %.2f\n", s.marks); return 0; }

The output of the above program will be:

yaml
Copy code
Roll No: 123 Name: John Doe Marks: 85.50

A union is similar to a structure, but it allows you to store multiple values of different data types in the same memory location. The general syntax for declaring a union in C is:

c
Copy code
union union_name { data_type1 variable1; data_type2 variable2; ... };

For example, the following code declares a union named value that holds either an integer or a float:

c
Copy code
union value { int i; float f; };

You can create variables of a union type using the union name and access its members using the dot operator (.).

For example, the following code creates a variable of type value named v and accesses its members:

c
Copy code
#include <stdio.h> union value { int i; float f; }; int main() { union value v; v.i = 123; printf("Integer value: %d\n", v.i); v.f = 123.456; printf("Float value: %.2f\n", v.f); return 0; }

The output of the above program will be:

sql
Copy code
Integer value: 123 Float value: 123.46

Note that when you access one member of a union, the values of the other members are lost. Unions are useful when you want to save memory by using the same memory location for different values of different data types.


    Leave a Comment


  • captcha text