Structures
A structure in C++ stores together data elements under a single name. The data elements, also called data members, can be of different data types.
Syntax
A structure is defined with:
- The
struct
keyword in the beginning. - Curly brackets
{
}
to define the body. - A semicolon
;
at the end.
struct name {
member1_type member1_name;
member2_type member2_name;
member3_type member3_name;
};
Example
The example below is a struct
with the name coder
:
struct coder {long id;char name[30];char username[15];};
This structure contains three members:
id
name
username
Declaring and Initializing Structure Variables
The members of a structure can be initialized inside the structure definition in C++11 and higher.
An example of declaring and initializing a structure variable:
#include <iostream>struct coordinates {int x;int y;};int main() {// Declaring variable c1struct coordinates c1;c1.x = 2;c1.y = 2;// Declaring and initializing variable c2struct coordinates c2 = { 0, 1 };std::cout << "x1 = " << c1.x << ", y1 = " << c1.y << "\n"; // For variable c1std::cout << "x2 = " << c2.x << ", y2 = " << c2.y << "\n"; // For variable c2return 0;}
The output will look like this:
x1 = 2, y1 = 2x2 = 0, y2 = 1
Array of Structure
Like other primitive data types, an array of structures can be created.
An example of array of structure:
#include <iostream>struct coordinates {int x;int y;};int main() {struct coordinates c[4];int i;for (i = 0; i < 4; i++)std::cin >> c[i].x >> c[i].y;for (i = 0; i < 4; i++) {std::cout << "x" << i+1 << "=" << c[i].x << "\t";std::cout << "y" << i+1 << "=" << c[i].y << "\n";}return 0;}
Input:
1 01 21 10 2
Output:
x1 = 1 y1 = 0x2 = 1 y2 = 2x3 = 1 y3 = 1x4 = 0 y4 = 2
Nested Structure
A structure’s variable can also be a member of, or nested in, another structure.
In the example below, a DOB
structure is nested in a coder
structure:
struct coder {long id;char name[30];char username[15];struct DOB {int month;int day;int year;} d;} bjarne;
The d
is the structure’s variable for struct DOB
and bjarne
is the structure variable for struct coder
.
Members of a nested structure can be accessed using var1.var2.member1
.
Initializing a member of the structure DOB
from the example above:
bjarne.d.day = 10;
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours