Variables in CPP (C Plus Plus)

By Prof. Fazal Rehman Shamil
Last modified on March 3rd, 2022

Variables in CPP (C Plus Plus)

A variable is used to store the values. The name of a variable is called an identifier. You can give a variable any name of your choice, as long as it is a valid identifier name and the Variable name must be descriptive.

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; (Example: int price)

data_type variable_name1, variable_name2, variable_name3; (Example: int a, b, c)

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.

Initialization of integers

Declaration and initialization on a different line

Initialization of Characters

RULES FOR NAMING VARIABLES

Rule 1:

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

Example:

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.

Example:

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

Rule 3:

Spaces or special characters are not allowed.

Example:

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.

Example:

float PRICE and float price both are different.

Rule 5:

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

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

SCOPE OF VARIABLE IN C++

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

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

 

Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.