Chapter 1: Variables in C++
Variables are one of the most fundamental concepts in programming. A variable is a named storage location in memory that holds data. The value stored in a variable can change while the program is running.
Think of a variable as a labeled container. You can store information inside it, read it later, or update it whenever needed.
For example:
- Store a person's age
- Store a student's name
- Store a product's price
- Store whether a user is logged in
Without variables, it would be impossible to create dynamic and interactive programs.
What is a Variable?
A variable reserves space in your computer's memory and associates that space with a name.
For example:
1int age = 20;
In this example:
intis the data type.ageis the variable name.20is the value stored in the variable.
Memory representation:
1Variable Name Value 2+-----------+ +------+ 3| age | -> | 20 | 4+-----------+ +------+
Declaring Variables
Before using a variable, you must declare it.
Syntax
1data_type variable_name;
Example:
1int age; 2float salary; 3char grade; 4bool isPassed;
Here, memory is allocated, but the variables do not yet have meaningful values.
Initializing Variables
Initialization means assigning a value when the variable is declared.
1int age = 22; 2float salary = 35000.50; 3char grade = 'A'; 4bool isPassed = true;
You can also assign a value later:
1int age; 2 3age = 22;
Multiple Variable Declaration
You can declare multiple variables of the same type in one statement.
1int x, y, z;
Initialization example:
1int a = 10, b = 20, c = 30;
Printing Variables
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int age = 22; 8 9 cout << age; 10 11 return 0; 12}
Output
122
Printing Multiple Variables
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 string name = "Ankit"; 8 int age = 22; 9 10 cout << "Name: " << name << endl; 11 cout << "Age: " << age; 12 13 return 0; 14}
Output
1Name: Ankit 2Age: 22
Changing Variable Values
Variables can be updated during program execution.
1int age = 20; 2 3age = 21; 4 5cout << age;
Output:
121
Variable Naming Rules
Choosing meaningful variable names improves code readability.
A valid variable name:
- Can contain letters, digits, and underscores (
_) - Must begin with a letter or underscore
- Cannot begin with a number
- Cannot contain spaces
- Cannot use special characters like
@,#,%,$ - Cannot use C++ keywords
Valid Variable Names
1int age; 2int studentAge; 3int total_marks; 4int number1; 5float averageScore;
Invalid Variable Names
1int 1age; // Starts with a number 2int total marks; // Contains a space 3int class; // Keyword 4int user-name; // Hyphen not allowed 5int @price; // Special character
Naming Conventions
Use descriptive names.
Good:
1int studentAge; 2double accountBalance; 3bool isLoggedIn;
Poor:
1int a; 2int x; 3double d;
Use camelCase for variables.
Example:
1int totalMarks; 2float accountBalance; 3bool isStudent;
C++ Keywords
Keywords are reserved words that have predefined meanings in C++. They cannot be used as variable names.
Examples:
1int 2float 3double 4char 5bool 6if 7else 8for 9while 10switch 11return 12class 13public 14private 15virtual 16const 17namespace 18using 19new 20delete
Incorrect:
1int return = 5;
Correct:
1int returnValue = 5;
Literals in C++
A literal is a fixed value written directly into your code.
Integer Literal
1100
1int marks = 100;
Floating-Point Literal
199.95
1float price = 99.95;
Character Literal
1'A'
1char grade = 'A';
String Literal
1"Hello"
1string message = "Welcome";
Boolean Literal
1true 2false
1bool status = true;
Constants
A constant is a value that cannot be changed after it has been initialized.
Using const
1const double PI = 3.14159;
Attempting to modify it:
1PI = 3.14;
Produces a compilation error.
Example
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 const double PI = 3.14159; 8 9 cout << PI; 10 11 return 0; 12}
Output:
13.14159
constexpr
constexpr creates compile-time constants.
1constexpr int DAYS_IN_WEEK = 7;
Unlike const, a constexpr value is evaluated during compilation when possible, which can improve performance.
Difference Between Variables and Constants
| Variable | Constant |
|---|---|
| Value can change | Value cannot change |
| Uses normal memory | Read-only after initialization |
| Suitable for dynamic data | Suitable for fixed values |
Example:
1int age = 20; 2 3age = 21;
1const int MAX_USERS = 100;
Common Beginner Mistakes
Using an Uninitialized Variable
Incorrect:
1int age; 2 3cout << age;
Always initialize variables:
1int age = 0;
Using Keywords as Variable Names
Incorrect:
1int class = 10;
Correct:
1int classNumber = 10;
Choosing Meaningless Names
Poor:
1int x; 2int y;
Better:
1int employeeAge; 2int totalSalary;
Best Practices
- Use descriptive variable names.
- Initialize variables when declaring them.
- Use
constfor values that never change. - Follow camelCase naming conventions.
- Avoid single-letter variable names except in simple loops.
- Keep names concise but meaningful.
Practice Exercises
Exercise 1
Create variables for your name, age, and city, then print them.
1#include <iostream> 2#include <string> 3 4using namespace std; 5 6int main() 7{ 8 string name = "Ankit"; 9 int age = 22; 10 string city = "Lucknow"; 11 12 cout << "Name: " << name << endl; 13 cout << "Age: " << age << endl; 14 cout << "City: " << city; 15 16 return 0; 17}
Exercise 2
Declare two integer variables and print their values.
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int a = 10; 8 int b = 20; 9 10 cout << a << " " << b; 11 12 return 0; 13}
Exercise 3
Declare a constant for the value of π and print it.
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 const double PI = 3.14159; 8 9 cout << PI; 10 11 return 0; 12}
Interview Questions
- What is a variable in C++?
- What is the difference between declaration and initialization?
- What are the rules for naming variables?
- What are literals in C++?
- What is the difference between
constandconstexpr? - Why should variables be initialized?
- Can a keyword be used as a variable name? Why or why not?
Summary
In this chapter, you learned:
- What variables are and why they are essential.
- How to declare and initialize variables.
- Rules and best practices for naming variables.
- What C++ keywords are.
- Different types of literals.
- How to use
constandconstexprto create constants. - Common mistakes to avoid when working with variables.
In the next chapter, you'll explore C++ Data Types, including int, float, double, char, bool, string, and auto, and learn how each type stores different kinds of data.