What is the Variables in C++ ? with Free Notes

What is the Variables in C++ ???

Variables in C++ are names as like keywords which are used for reserving memory to hold some data so that we don’t have need to remember the numbers of memory location/address like 46735 and instead we can use the memory location by simply referring to the variable name. Every variable have a unique memory address. For example, if we have 3 variables naming v1, v2, v3. They may be assigned the memory addresses 32000, 12456, 67893 respectively. Variables name follow same naming convention as of identifier.

Therefore, we can define “a variable as a portion of memory to store a determined value.” Variable Follows the rule of the identifiers that distinguishes it from the others.

Declaring Variables

A Variable in C++ must be declared (the type of variable) before it can be used in a program. Following shows how to declare a variable.

Syntax:

Datatype <variable name>;

Datatype is valid type of data like int, float, char etc, and variable is the name of the variable.

Example:

int a;
float b;

These are two valid declarations of variables. The First one declares a variable of type int with the identifier a. Th Second one declares a variable of type float with the identifier b. Once declared, the variable a and b can be used within the rest of their scope (a variable can use only in their declaring scope) in the program. We can declare more then one variable in a single statement. We can declare all of them in a single statement by separating their identifiers with commas.

Syntax:

Datatype variable1, variable2, variable3,......variableN;

Example:

int a, b, c;
Variables in C++ Language

Initializations of variables

There are two ways to initialize a variable in C++:

  1. In first way a variable is declare with initial value. like:
type variable = initial_value;

For example, if we want to declare an integer variable called “a” and initialized with a value of 0 at the moment in which it is declared, we could write:

int a = 0;

2. The other way to initialize variables in two steps, declare the variable without assigning initial value and latter assign value when required like:

type variables;
variable = value;

For Example:

int a;
a = 0;

Both ways of initializing variables are valid and equivalent in C++.

Variable Scope

We can declare a variable in a program anywhere but generally we declare a variable inside of the main() function. Such a variable could be used only inside of the Curly brackets() of main(). In Some cases we may want to declare a variable that can be accessed from one referred to as its scope. A variable have different scopes.

  1. local variables
  2. global variables
  3. namespace

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top