C++ Variables
A variable in C++ is a named place in memory that stores a value. Programs use variables to remember information, calculate with it, and print it later.
Every C++ variable has a type, a name, and a value. The type tells C++ what kind of data the variable can store, such as a whole number or a decimal number.
Declaring Variables
To create a variable, write its type followed by its name. This is called declaring a variable.
#include <iostream>
int main(void) {
int apples = 6;
double price = 0.75;
char grade = 'A';
std::cout << "Apples: " << apples << std::endl;
std::cout << "Price: $" << price << std::endl;
std::cout << "Grade: " << grade << std::endl;
apples = 8;
std::cout << "Updated apples: " << apples << std::endl;
return 0;
}
Output:
Apples: 6
Price: $0.75
Grade: A
Updated apples: 8
How It Works
The statement int apples = 6; creates a variable named apples. Its type is int, which stores whole numbers, and its starting value is 6.
The statement double price = 0.75; stores a number with a decimal point. The statement char grade = 'A'; stores one character. A char value uses single quotes, while printed text uses double quotes.
After a variable exists, you can use its name in output. For example, std::cout << apples; prints the current value stored in apples.
Changing a Variable
You can assign a new value to an existing variable with the assignment operator, =. In the example, apples = 8; replaces the old value 6 with the new value 8.
Do not repeat the type when you are changing a variable that has already been declared. Write apples = 8;, not int apples = 8; in the same scope.
Declaration and Initialization
Declaration means creating the variable name and type. Initialization means giving the variable its first value.
You can do both at once, as in int score = 10;. This is usually the clearest choice for beginners because the variable starts with a known value.
You can also declare first and assign later:
int score;
score = 10;
This is valid, but avoid using a variable before it has been given a value.
Variable Names
A C++ variable name can contain letters, digits, and underscores, but it cannot start with a digit. Variable names are case-sensitive, so score and Score are different names.
Choose names that explain what the value means. Names like total, age, and itemCount are easier to understand than names like x or n when the program grows.
Common Mistakes
- Forgetting the semicolon after a declaration or assignment.
- Using a variable before declaring it.
- Assigning a decimal value to an
intwhen you meant to keep the decimal part. - Writing a variable name with different capitalization by accident.
- Trying to change a variable’s type after it has already been declared.
Takeaway: declare a variable with a type and a name, initialize it with a useful starting value, and use assignment when its value needs to change.
