Lesson 9 of 60 – Variables in C++
15%

Variables in C++

A variable is a named storage location used to hold a value that a program can use and, when appropriate, modify during execution. Every variable has a data type that determines what kind of value it can store.

Note: Before using a variable, you normally declare it with a data type and a name. You can also initialize it at the time of declaration.

1. What is a Variable?

A variable is a named location used to store data. For example:

int age = 20;

Here, age is a variable that stores the integer value 20.

2. Why Do We Use Variables?

Variables allow a program to store information and use that information later.

  • Store numbers
  • Store characters
  • Store text
  • Store true or false values
  • Store calculated results
  • Store user input

3. Declaring a Variable

Variable declaration tells the compiler the variable's data type and name.

int age;

Here:

  • int is the data type.
  • age is the variable name.

4. Initializing a Variable

Initialization means giving a variable an initial value when it is created.

int age = 20;

The variable age is declared and initialized with the value 20.

5. Declaration and Assignment Separately

A variable can be declared first and assigned a value later.

int age;

age = 20;

The first statement declares the variable and the second statement assigns a value to it.

6. Basic Variable Types

C++ provides several fundamental data types that can be used for variables.

  • int – integer values
  • float – single-precision floating-point values
  • double – double-precision floating-point values
  • char – a character
  • bool – true or false

7. Integer Variable

An int variable is used to store integer values.

int age = 20;
int marks = 85;

Integer values do not contain a fractional part.

8. Floating-Point Variable

A float variable can store a floating-point value.

float price = 99.50f;

The f suffix indicates a float literal.

9. Double Variable

The double type is commonly used when more precision is needed than a typical float.

double salary = 25000.75;

10. Character Variable

A char variable stores a character.

char grade = 'A';

Character literals are commonly written using single quotation marks.

11. Boolean Variable

A bool variable represents a Boolean value: true or false.

bool passed = true;

12. String Variable

The C++ standard library provides std::string for storing text. It is available through the <string> header.

#include <string>

std::string name = "Rahul";

13. Multiple Variables

You can declare multiple variables of the same type in one statement.

int age = 20, marks = 80;

However, declaring related variables separately can sometimes make code easier to read.

14. Assigning a New Value

A variable's value can be changed by assigning a new value to it.

int age = 20;

age = 25;

After the second statement, age contains 25.

15. Using Variables in Calculations

Variables can be used in arithmetic expressions.

int a = 10;
int b = 20;

int sum = a + b;

std::cout << sum;

The variable sum stores the result of the addition.

16. Displaying a Variable

The value of a variable can be displayed using std::cout.

#include <iostream>

int main() {

    int age = 20;

    std::cout << age;

    return 0;
}

17. Displaying Text and Variables

#include <iostream>

int main() {

    int age = 20;

    std::cout << "Age = " << age;

    return 0;
}

Multiple values can be sent to std::cout using the << operator.

18. Taking Input into a Variable

The std::cin object can be used to store user input in a variable.

#include <iostream>

int main() {

    int age;

    std::cout << "Enter your age: ";
    std::cin >> age;

    std::cout << "Age = " << age;

    return 0;
}

19. Constant Variables

The const keyword can be used when a variable should not be modified after initialization.

const double PI = 3.14159;

Attempting to modify a const object after initialization is not allowed.

20. Naming Variables

Variable names should be meaningful and follow C++ identifier rules.

int studentAge = 20;
double courseFee = 5000;

Meaningful names make programs easier to understand.

21. Valid Variable Names

Examples of valid variable names:

age
studentAge
student_age
marks1
totalMarks

These names follow the basic identifier rules.

22. Invalid Variable Names

Examples of invalid variable names:

2age
student name
my-name
class

A variable name cannot begin with a digit, contain spaces or hyphens, or be a reserved C++ keyword.

23. Case-Sensitive Variables

C++ is case-sensitive, so these are different variables:

int age = 20;
int Age = 30;
int AGE = 40;

It is generally better to use a consistent naming style in a project.

24. Local Variables

A variable declared inside a function or block is generally a local variable. Its scope is limited to that function or block.

int main() {

    int age = 20;

    std::cout << age;

    return 0;
}

25. Global Variables

A variable declared outside functions is a global variable. Its scope and lifetime differ from those of local variables.

#include <iostream>

int count = 10;

int main() {

    std::cout << count;

    return 0;
}

Global variables should be used carefully because they can be accessed from multiple parts of a program depending on their linkage and scope.

26. Variable Scope

Scope describes the region of a program where a name can be used.

int main() {

    int age = 20;

    if (age > 18) {

        int bonus = 5;

        std::cout << bonus;
    }

    return 0;
}

The variable bonus is declared inside the if block and its scope is limited to that block.

27. Variable Initialization Styles

C++ supports several initialization forms.

int a = 10;

int b(20);

int c{30};

Brace initialization is a modern C++ style and can help prevent certain narrowing conversions.

28. Auto Variables

Modern C++ provides the auto keyword for type deduction. The compiler determines the variable's type from its initializer.

auto age = 20;
auto price = 99.50;

In the first example, age is deduced as an integer type, while the second is deduced as a floating-point type.

29. Variables Example

#include <iostream>
#include <string>

int main() {

    std::string name = "Rahul";
    int age = 20;
    double marks = 85.5;
    char grade = 'A';
    bool passed = true;

    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Marks: " << marks << std::endl;
    std::cout << "Grade: " << grade << std::endl;
    std::cout << "Passed: " << passed << std::endl;

    return 0;
}

This program demonstrates variables of several common C++ types.

30. Variables – Final Summary

Variables are fundamental to C++ programming. They allow programs to store, process, modify, and display data.

Type Example Purpose
int int age = 20; Integer values
float float price = 10.5f; Floating-point values
double double salary = 25000.75; Floating-point values with more precision
char char grade = 'A'; Single character
bool bool passed = true; Boolean value
std::string std::string name = "Rahul"; Text

📌 Key Points

  • A variable stores a value under a name.
  • Variables are normally declared with a data type and a name.
  • Initialization gives a variable its initial value.
  • Variables can be changed by assigning new values when they are not const.
  • C++ provides types such as int, float, double, char, and bool.
  • std::string can be used to store text.
  • Variable names must follow C++ identifier rules.
  • C++ variable names are case-sensitive.
  • const can be used for values that should not be modified.
  • auto can be used for type deduction in modern C++.
  • Variable scope determines where a variable can be accessed.

🧠 Quick Quiz

Question: Which keyword is commonly used to declare an integer variable in C++?