Variables in C++

What is a Variable?

A variable in C++ is like a storage box where you can keep data. Think of it as a label that holds a value, such as a number or a word, which your program can use and change.

Declaring a Variable

To create a variable, you need to specify its type (what kind of data it will hold) and give it a name.


#include <iostream>
using namespace std;

int main() {
    int age = 25;  // Declaring an integer variable called 'age' and assigning it a value
    cout << "My age is: " << age << endl;
    return 0;
}
            

Common Variable Types

Changing Variable Values

Once you declare a variable, you can change its value later in the program.


#include <iostream>
using namespace std;

int main() {
    int score = 10;
    cout << "Initial score: " << score << endl;

    score = 20; // Changing the value
    cout << "Updated score: " << score << endl;

    return 0;
}
            

Rules for Naming Variables

Try It Yourself!

Create a program that declares different types of variables and prints them to the screen.