Gal Normal

I've learned some intermediate programming concepts. What else is there?

Geek Curious

How about structs? They're an important concept in some programming languages!

Gal Excited

Sounds cool! Teach me how to use structs!

Geek Smiling

Sure! Let's learn structs using C++.

Step 1: Defining a Struct

Gal Eager

First, how do we define a struct?

Geek Explaining

A struct is a custom data type that can group multiple variables of different data types. Here's how you define a struct.

#include <iostream>
#include <string>

struct Person {
    std::string name;
    int age;

Step 2: Creating Struct Instances

Gal Wondering

Now that we've defined a struct, how do we create instances of it?

Geek Ready

You create instances like you would with any other data type. Let me show you an example.

Person person1; = "Alice";
person1.age = 30;

Person person2; = "Bob";
person2.age = 25;

Step 3: Accessing and Modifying Struct Members

Gal Curious

How do I access and modify the data in a struct?

Geek Smiling

You can access and modify struct members using the dot (.) operator. Let's try it out!

std::cout << << " is " << person1.age << " years old." << std::endl;
std::cout << << " is " << person2.age << " years old." << std::endl;

person1.age += 1;
std::cout << << " is now " << person1.age << " years old." << std::endl;


Alice is 30 years old.
Bob is 25 years old.
Alice is now 31 years old.


You’ve learned how to use structs in C++! Structs are a powerful way to organize and group data of different types together. Keep practicing and exploring other intermediate programming concepts! 🚀