FPCPP C3
FPCPP C3
FUNDAMENTALS OF
3
PROGRAMMING IN C++
STRUCTURES, UNIONS AND
ENUMERATIONS
Structures 2
Structures are a collection of data items of different types.
Structures can also be seen as a way of creating user defined data types.
Syntax:
struct structure_tag{
// member variables
};
• In the above syntax:
• The keyword struct declares this is a structure definition.
• The name of the structure definition is called structure tag.
• Structure tag is a legal identifier (or name) of the structure to be defined.
• The structure definition must placed outside any block at the global scope.
… 3
• Once a structure has been defined, it can be used just like the predefined types.
• Example:
struct complex {
struct complex { int img;
int img; int real;
int real; };
}num1, num2; complex num1, num2;
• Accessing member values (or variables) of a structure can be done using dot(.) operator.
num1.img=2;
• Its possible to copynum1.real=4;
a structure variable to another structure variable of the same type. Like
num2 = num1;
Initializing… 4
• A structure variable can be initialized at the time that it is declared.
• To give a structure variable a value,
• you follow it by an equal sign and a list of the member values enclosed in braces.
• E.g. complex num3 = {7, 6};
• It is an error if there are more initializers than struct members and if orders don’t match.
• If there are fewer initializer values than struct members, the provided values are used to initialize
data members, in order.
• The remaining will be assigned to default values.
Nested structures… 5
• We can have a structure definition inside another structure declaration called nested structure.
• E.g.
• struct person{
• struct student{
• string name;
• string dept;
• int age;
• string ID;
• string birthplace;
• person pratts;
• };
• };