User defined data types in c++(Structure and Union)
Basically, the data types are categorised into two types. One is the primitive data types supported by programming language. Another one is user defined datatypes which is created by the user.
Some the user defined datatypes in c++ are given below.
- · Structures
- · Unions
Let us implement each one of this.
Structures:
It is one
of the user defined data types in c++, which has collection of members of
different datatypes.
Syntax:
Creating a structure:
Structure structure_name
{
Data type
data_member1;
Data
type data_member2;
………………………………………
Data
type data_membern;
}
Variable creation:
The structure
variable is created by as follows..
Structure_name
variable_name;
To assign values: Structure_name variable_name= {value1,value2,…….,valuen};
To access variables: structure_name.value1;
C++ Sample Code:
#include <bits/stdc++.h>
using namespace std;
// Define structure
int id;
char name[20];
char s_class[3];
};
int main() {
// Two objects
are created and assigned with value
student s1 = {1,
"Ajay","I"};
student s2 = {2,
"Jey", "II"};
// Print the
values
cout <<
s1.id <<" "<<s1.name <<" "
<<s1.s_class<< endl;
cout <<
s2.id <<" "<<s2.name <<" "
<<s2.s_class<< endl;
return 0;
}
Output:
1 Ajay I
2 Jey II
Unions:
This is
another user defined data structures in which data members share the total
memory of union.
The structure and union are similar,only different is the
memory space.
Syntax:
Union union_name {
Datatype data_member1;
Datatype data_member2;
……………………………………..
Datatype
data_membern;
}
Object creation: union_name variable_name;
Accessing the object: variable_name. data_member;
C++ sample Code:
#include <bits/stdc++.h>
using namespace std;
// Define union
int id;
char s_class;
};
int main() {
// Two objects
are created and assigned with value
student s1;
s1.id = 1;
cout<<"Id:" <<s1.id <<endl;
s1.s_class = 'I';
cout <<
"Class:" <<s1.s_class<<endl;
cout <<
s1.id <<" "<<s1.s_class<< endl;
return 0;
}
Output:
Id:1
Class:I
73 I
Here, the memory is restricted. So, the id is printed a ascii
value of ‘I’.
These are the user defined data types structures and unions.
Hope ,you understood the syntax and coding samples. Keep Coding!!!
Comments
Post a Comment