C++ Structures

C++ Structures (structs)

Structures (also called structs) are a way to group several related variables into one place. Unlike an array, a structure can contain many different data types (int, string, bool, etc.).

Creating a Structure

To create a structure, use the struct keyword and declare each of its members inside curly braces.

Example

struct {
  int myNum;
  string myString;
} myStructure;

Accessing Structure Members

To access members of a structure, use the dot syntax (.):

Example

#include <iostream>
#include <string>
using namespace std;

int main() { struct { int myNum; string myString; } myStructure;

// Assign values to members myStructure.myNum = 1; myStructure.myString = "Hello World!";

// Print members cout << myStructure.myNum << "\n"; cout << myStructure.myString << "\n"; return 0; }

Structures help you organize complex data like user profiles, game entities, and configurations logically.


Exercise

?

Which syntax is used to access members of a structure in C++?