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
- int – Stores whole numbers (e.g.,
int age = 25;
) - double – Stores decimal numbers (e.g.,
double price = 9.99;
) - char – Stores a single character (e.g.,
char grade = 'A';
) - string – Stores text (e.g.,
string name = "John";
) - bool – Stores true or false values (e.g.,
bool isStudent = true;
)
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
- Variable names can contain letters, numbers, and underscores (_).
- They cannot start with a number.
- They cannot contain spaces or special characters.
- They are case-sensitive (
Age
andage
are different).
Try It Yourself!
Create a program that declares different types of variables and prints them to the screen.