Variables in CPP (C Plus Plus)

Variables in CPP (C Plus Plus)

variable provides named storage that manipulates the program. The name of a variable is called an identifier.  It should be a related name. You can give a variable any name you want, as long as it is a valid identifier. Variables are used to store data.

Every variable must have the name, type, size, value, and address.

Name — a variable name like the price

Type — variable type like integer, string

Size — determined by the type

Value — the data stored in the variable’s memory location

Address — the starting location in memory where the value is stored.

Syntax of variable declaration

data_type variable_name;

data_type variable_name1, variable_name2, variable_name3;

Examples of variable declaration

int    marks;

char   ch;

float  unit;

double meter_to_cm;

int marks;

int chemistry_marks, computer_marks;

Variable Initialization

Variables can be initialized with values.

int marks=600;

int number;



Rule 1:

All variable names must start with an alphabet or an Underscore ( _ ).


char _price;

float cost;

Rule 2:

After the first initial letter, variable names can also contain numbers. A variable name can’t start with a number.


“a1” variable name is legal but  “1a” is not a legal name.

Rule 3:

Spaces or special characters are not allowed.


float product price //wrong variable name because it has space in the variable name.

float product_price //Correct variable name because it has no space in the variable name.

Rule 4:

Uppercase characters are distinct from lowercase characters.


float PRICE and float price both are different.

Rule 5:

You cannot use a C++ keyword (a reserved word) as a variable name.

float char; // “char” is a wrong variable name. char is a keyword and it is not allowed in the variable name.


Local Variable

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.

Example of Local Variable

#include <iostream> //header file

using namespace std;

int main () {  //main

float price; //Local variable declaration:

cout << price; //output

return 0;


Global Variable

Global variables are variables that are often declared outside the main() function. The variable scope is the full file where the variable is defined.

The global variable can be defined as below.

Example of Global Variable

#include <iostream> //header file

using namespace std;

float price; //Global variable declaration:

int main () {  //main

cout << price; // output

return 0;


Prof. Fazal Rehman Shamil
Latest posts by Prof. Fazal Rehman Shamil (see all)

    Buy advertisement space on T4Tutorials

    For more details email [email protected]