cpp / beginner
Snippet
Structures: Grouping Related Data
A struct groups multiple variables of different types under one name. Each variable within the struct is called a member. Access members using the dot operator. Structs are useful for representing records like a player in a game.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>using namespace std;struct Player {string name;int health;float score;};int main() {Player player1;player1.name = "Alex";player1.health = 100;player1.score = 2450.5f;cout << player1.name << " has " << player1.health << " HP" << endl;return 0;}
Breakdown
1
struct Player { ... };
Defines a structure with three members: name, health, and score
2
player1.name = "Alex";
Accesses the name member using the dot operator