Small Steps V — Making Your Own Types
Grouping related values
Group related values.
What you will learn
struct defines a new type grouping related values. Put a name and score together in one Player.
Try it
Example · example1.cpp
struct Player
{
String name;
int score;
};
void small_main()
{
Player player;
player.name = "Alex";
player.score = 1200;
print(player.name, ": ", player.score);
}
String and int are existing types; Player is a type we create. Access the values inside it with a dot, as in player.name.
The example prints Alex: 1200. A struct definition needs a ; after its closing brace.
Exercise
Create a Point struct with double x and y. Store (3.5, 7.0) and print the values.
Exercise starter · exercise1_starter.cpp
struct Point
{
// Add x and y here.
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}
Hint
Start with struct Point { double x; double y; };.
show solution
struct Point
{
double x;
double y;
};
void small_main()
{
Point point;
point.x = 3.5;
point.y = 7.0;
print(point.x, ", ", point.y);
}