Variables in C++
In our previous lessons, we explored basic statements and expressions, even building a multiplication table. However, you might have noticed a problem: if you wanted to change a "2 times table" into a "5 times table," you had to manually update every single line. This is repetitive and unprofessional. To solve this, we use Variables.
Variables in C++
Quick Start: Key Definitions
Before we dive deep, let's define our core concepts in the simplest terms:
Terms |
Definations |
| Variable | A named "container" or "shelf" in your computer's memory that holds a specific value. |
| Variable Declaration | The act of telling the computer to reserve a spot in memory and give it a name. |
| Variable Initialization | Giving a variable its very first value at the exact moment you create it. |
| Assignment | Giving a variable a value later in the program, after it has already been declared. |
| Data Type | A label that tells the computer how much space a variable need and what "kind" of data (numbers, letters, etc.) it will hold. |
| Identifier | The unique name you choose for your variable. |
The "Cupboard" Analogy: What is a Variable?
Imagine you have a large almirah (cupboard) at home with many empty shelves.
- Selection: You find an empty shelf and decide to keep your "C++ Books" there.
- Tagging: You put a label on that shelf that says "C++ Books". Even if the shelf is empty for now, that space is reserved for those books.
- Capacity: Every shelf has a limit. You can only fit as many books as the shelf's size allows.
In C++, your computer’s RAM (Memory) is the cupboard, and a variable is that tagged shelf. It has a name (the tag) and a capacity (the data type).
Variable Declaration: Reserving Memory
To use a variable, you must first declare it so the compiler knows to reserve space in the RAM.
The Syntax: type identifier; or type name;
Example: int num; Here, int is the type (telling the computer to store integer numbers), and num is the name. At this stage, the space is reserved, but it might contain "garbage values" (leftover random data) until you give it a value.
Initialization vs. Assignment
How do you put data into your "container"? There are two main ways:
Initialization:
Providing a value at the time of creation.
◦ Standard: int num = 2;
◦ Safe Initialization (Braces): int num{2};
Assignment:
Giving a value later in the code.
◦ int num; (Declaration)
◦ num = 5; (Assignment)
Pro Tip for Students: Using curly braces {} is considered a "best practice". If you try to store a decimal (like 2.3) in an int using =, the computer might just ignore the .3. However, using {2.3} will cause the compiler to give you an error, helping you catch bugs early! Additionally, leaving braces empty int num{}; automatically stores a default value like 0.
Rules for Naming Your Variables
You cannot name a variable just anything. C++ has specific rules (and some good advice) for identifiers:
- Start with a Letter: The first character must be an alphabet letter (A-Z or a-z).
- No Special Characters: You cannot use symbols like @ or #. The only exception is the underscore (_).
- No Spaces: Spaces are not allowed. Instead of int my num;, use int my_num; or int myNum;.
- No Reserved Keywords: You cannot use words like int or main as names because they already have special meanings in C++.
- Be Descriptive: While you could name a variable x, it is better to use a name like tableValue so you know exactly what it’s for.
-
Using Variables with cout
When you want to display your variable's value using cout, you must be careful with double quotes.
- cout << "num"; → This prints the literal word num.
- cout << num; → This prints the value stored inside the variable (e.g., 5).
By using the variable name without quotes, you can update your entire multiplication table by changing just one line of code.
//This program will demonstrate how to decleare variables in C++ # include <iostream> using namespace std; int main(){ int x=20; //Initialize an integer type variable with name x //(not descriptive = not a good practice) float pi; //Declares an integer type variable with name age //(descriptive= good practice) int age; //Declares an integer type variable. It can have garbage value for now. //garbage means any integer number between, -2,147,483,648 to 2,147,483,647 //(this is the range of values a int typed variable can store) string blood_group= "B+ve"; //initialize the string typed name blood_group //and assigns value B+ve age=30; //assignment, now the variable holds integer value 30 pi=3.14159; cout<<"The value of x is: "<<x<<endl; //Note: We are using the variable name //within the code as well as without double quotes, //but the value stored in the variable will only appear where the variable name //is without double qoutes cout<<"The value of pi is: "<<pi<<endl; cout<<"Your age is: "<<age<<endl; cout<<"Your blood group is: "<<blood_group<<endl; return 0; }
Output:
The value of x is: 20
The value of pi is: 3.14159
Your age is: 30
Your blood group is: B+ve
Try It Yourself!
Challenge 1 (Reflection): Why is it better to initialize a variable with a value like 0 rather than leaving it empty? (Hint: Think about "garbage values").
Challenge 2 (Coding): Write a single line of C++ code to declare an integer named daysInYear and initialize it to 365.
Challenge 3 (Identify the Error): Which of these variable names will cause an error?
- student_age
- 2ndPlace
- totalAmount
- int
Join the Conversation: What is your biggest C++ fear? Is it the syntax, or perhaps the logic? Share your thoughts in the comments below!
Analogy Recap: Think of a variable as a labeled jar in a kitchen. The label tells you what’s inside, and the size of the jar tells you how much it can hold. If you put a new label on it or change the contents, the old contents are gone—jars can only hold one thing at a time.
