Understanding Variables
COS1511 - Introduction To Programming I · Learning C++
Understanding Variables
What is a Variable?
A variable is a named storage location in memory that holds data which can change while the program is running. Variables are one of the most important building blocks in C++.
Declaring Variables
In C++, variables must be declared before they are used. A declaration tells the compiler the variable's type and name. The type indicates what kind of data the variable can hold.
Here are some examples of variable declarations:
int age = 21; // Stores a whole number
double price = 19.99; // Stores decimal numbers
char grade = 'A'; // Stores a single character
string name = "Tyro"; // Stores textCommon Variable Types
Here are some common variable types in C++:
- int – Stores integers such as 1, 25, or -10.
- float – Stores decimal numbers with less precision.
- double – Stores decimal numbers with higher precision.
- char – Stores a single character like 'A'.
- bool – Stores true or false values.
- string – Stores text or words.
Rules for Naming Variables
When naming variables, you should follow these rules:
- Variable names cannot contain spaces.
- Names cannot start with numbers.
- Use meaningful names like
studentAgeinstead ofx. - C++ is case-sensitive.
Ageandageare different variables.
Remember: Always choose meaningful variable names to make your code easier to understand.
Updating Variables
Variables can change during program execution. Here is an example:
int score = 10; // score contains 10
score = 20; // score now contains 20Example Program
Here is a simple program that demonstrates declaring and using variables:
#include <iostream>
using namespace std;
int main() {
string name = "Tyro";
int age = 21;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
return 0;
}This program declares two variables: name and age. It then prints their values to the console.
Watch out: Ensure that you declare your variables before using them in your code. Otherwise, you will get a compilation error.
Summary
- A variable is a named storage location in memory.
- Variables must be declared before use.
- Common variable types include int, float, double, char, bool, and string.
- Follow naming rules to create meaningful variable names.
- Variables can be updated during program execution.
Check your understanding
- What is a variable in C++?
- List three common variable types and their uses.
- What are the rules for naming variables?
- Write a simple C++ program that declares two variables and prints their values.