C++ struct Keyword
Example
// Create a structure variable called myStructure
struct {
int myNum;
string myString;
} myStructure;
// Assign values to members of myStructure
myStructure.myNum = 1;
myStructure.myString = "Hello World!";
// Print members of myStructure
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";
Definition and Usage
The struct
keyword defines a structure. Structures are a way to group several related variables into one place.
If a structure has a name it can be used as a data type for any number of variables.
Syntax
struct structName {
type1 name1;
type2 name2;
...
} varName1, varName2, ...
If a structName is provided, it can be used as a data type for variables which will contain the structure. If the structure does not have a name, it can still be assigned directly to one or more variables (varName1, varName2, ...) declared after the struct.
The struct contains one or more members, each with a data type (type1, type2, ...) and a name (name1, name2, ...).
Related Pages
Read more about structures in our C++ Structures Tutorial.