Concept of Structure and Union or Declaration and Initialization of structure and union with example
#Concept of Structure Union or Declaration and Initialization of structure and union with example
Basically this article help us to understand the declaration and initialization of structure and union with example:
Assume for the moment that we must keep student data, such as name, age, address, and ID.
Making a separate variable for each attribute would be one method to accomplish this, but if you want to store the data for more than one student, you would have to make these several variables for every student.
This method of storing data is highly laborious.
A user can use the struct statement to define a structure. This statement determines a new data type.
#include <stdio.h>
#include <string.h>
int main() {
// Write C code here
printf("Hello world");
struct Person {
char name[60];
int age;
float height;
};
struct Person person1;
strcpy(person1.name, "developerIndian");
//person1.name="developerIndian"
person1.age = 225;
person1.height = 175.5;
printf("%s",person1.name); printf(" ");
printf("%d",person1.age); printf(" ");
printf("%f",person1.height); printf(" ");
return 0;
}
A union is an assemblage of various kinds of data items in one unit. It is an assortment of datatype variables, both derived and primitive. We can make user-defined data type elements by utilizing a union. The maximum size of a member variable determines the size of a union. It is advised to use the union in the implementation if we are only going to be manipulating one member of the data.
#include <stdio.h>
#include <string.h>
union DataStudent
{
int i;
float f;
char str[20];
};
int main ()
{
union Data data;
data.i = 10;
printf ("data.i : %d\n", data.i);
data.f = 220.5;
printf ("data.f : %f\n", data.f);
strcpy (data.str, "Developer Indian Programming");
printf ("data.str : %s\n", data.str);
return 0;
}
In the case of a Structure,Altering the values of a single member does not affect the other members of a Structure.
In the case of a Structure, a user can initialize multiple members at the same time
In the case of a Union When you alter the values of a single member, it affects the values of other members
In the case of a Union, a user can only initiate the first member at a time.
In this article ,we learn structures and unions are used to define custom data types that can store multiple variables of different types.
Both structures and unions are powerful tools for organizing and manipulating data in C, and the choice between them depends on the specific requirements of your program.