Struct basics in C++

Level 3125 keystrokes

A struct groups related values into one type. Point has the members x and y; p is initialized to {10, 20}, printed, and then x is changed to 30.

C++ code

// Defines a new type Point with two int members
1struct Point {
2 int x;
3 int y;
// A struct definition must end with a semicolon
4};
5
// Aggregate initialization: the values are assigned to x and y in order
6Point p = {10, 20};
// The dot operator accesses a member: prints 10
7cout << p.x << endl;
// Prints 20
8cout << p.y << endl;
// Members can be changed after initialization
9p.x = 30;
// Prints the new value 30
10cout << p.x << endl;

Output

10
20
30
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • ;× 8
  • .× 4
  • {× 2
  • }× 2
  • =× 2
  • ,× 1

More C++ examples at level 3

← C++ typing practice