C++ Variables

In C++, a variable is used to store data that can be used and modified during program execution. Each variable has a name, a type, and a value.

Before using a variable, it must be declared with a specific data type.

Variable Declaration

To declare a variable in C++, you need to specify the data type followed by the variable name.

int age;

In this example:

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

Variable Initialization

You can assign a value to a variable when declaring it. This is called initialization.

int age = 25;

Example Program

#include <iostream>
using namespace std;

int main() {

    int age = 25;

    cout << "Age: " << age;

    return 0;
}

Output

Age: 25

Multiple Variable Declaration

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

int x = 5, y = 10, z = 15;

Rules for Naming Variables

  • Variable names must start with a letter or underscore (_).
  • Variable names cannot start with a number.
  • Variable names cannot contain spaces.
  • Variable names cannot use C++ reserved keywords.
  • Variable names are case-sensitive.

Example of Valid Variable Names

int total;
int studentAge;
int _count;

Example of Invalid Variable Names

int 1value;   // cannot start with number
int total amount;  // space not allowed

Next Topic

Next, learn about C++ Data Types.