capypad
0 day streak
cpp / beginner
Snippet

Structures: Grouping Related Data

A struct groups different data types under one name. Unlike classes, struct members are public by default. Use structs when you need a simple data container without complex behavior.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
 
struct Player {
char name[50];
int health;
float score;
};
 
int main() {
Player player1;
player1.health = 100;
player1.score = 1500.5f;
 
Player player2 = {"Alice", 75, 2300.0f};
 
std::cout << player1.name << ": " << player1.health << " HP" << std::endl;
std::cout << player2.name << ": " << player2.health << " HP" << std::endl;
 
return 0;
}
Breakdown
1
struct Player { ... };
Defines a structure with three members: name, health, score
2
Player player1;
Creates an instance of the Player struct
3
player1.health = 100;
Access and assign values using the dot operator
4
Player player2 = {"Alice", 75, 2300.0f};
Initialize struct with values in declaration order