A variable is a name given to a memory location. It is the basic unit of storage in a program.
- The value stored in a variable can be changed during program execution.
- A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
- In C++, all the variables must be declared before use.
How to declare variables?
A typical variable declaration is of the form:
// Declaring a single variable type variable_name; // Declaring multiple variables: type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers and the underscore ‘_’ character. However, the name must not start with a number.
In the above diagram,
datatype (Links to an external site.): Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable float simpleInterest; // Declaring integer variable int time, speed; // Declaring character variable char var;
Difference between variable declaration and definition
The variable declaration refers to the part where a variable is first declared or introduced before its first use. A variable definition is a part where the variable is assigned a memory location and a value. Most of the times, variable declaration and definition are done together.
See the following C++ program for better clarification:
- CPP
#include <iostream> using namespace std;
int main()
{ // declaration and definition
// of variable 'a123'
char a123 = 'a' ;
// This is also both declaration and definition
// as 'b' is allocated memory and
// assigned some garbage value.
float b;
// multiple declarations and definitions
int _c, _d45, e;
// Let us print a variable
cout << a123 << endl;
return 0;
} |
a
Types of variables
There are three types of variables based on the scope of variables in C++ (Links to an external site.):
- Local Variables
- Instance Variables
- Static Variables
Let us now learn about each one of these variables in detail.
-
Local Variables: A variable defined within a block or method or constructor is called local variable.
- These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
- The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.
- Initialisation of Local Variable is Mandatory.
-
Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
- As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
- Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
- Initialisation of Instance Variable is not Mandatory.
- Instance Variable can be accessed only by creating objects.
-
Static Variables: Static variables are also known as Class variables.
- These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword (Links to an external site.) within a class outside any method constructor or block.
- Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
- Static variables are created at the start of program execution and destroyed automatically when execution ends.
- Initialization of Static Variable is not Mandatory. Its default value is 0
- If we access the static variable like Instance variable (through an object), the compiler will show the warning message and it won’t halt the program. The compiler will replace the object name to class name automatically.
- If we access the static variable without the class name, Compiler will automatically append the class name.
Instance variable Vs Static variable
- Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
- Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In case of static, changes will be reflected in other objects as static variables are common to all object of a class.
- We can access instance variables through object references and Static Variables can be accessed directly using class name.
- Syntax for static and instance variables:
class Example { static int a; // static variable int b; // instance variable }
Different ways to initialize a variable in C/C++
Variables (Links to an external site.) are arbitrary names given to a memory location in the system. These memory locations addresses in the memory. Suppose we want to save our marks in memory. Now, these marks will get saved at a particular address in the memory. Now, whenever these marks will be updated, they will be stored at a different memory address. Thus, to facilitate the fetching of these memory addresses, variables are used. Variables are names given to these memory locations. The memory location referred to by this variable holds a value of our interest. Now, these variables once declared, are assigned some value. This assignment of value to these variables is called initialization of variables.
Initialization of a variable is of two types:
- Static Initialization: Here, the variable is assigned a value in advance. This variable then acts as a constant.
- Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of this variable can be altered every time the program is being run.
Different ways of initializing a variable in C
Method 1 (Declaring the variable and then initializing it)
int a; a = 5;
Method 2 (Declaring and Initializing the variable together):
int a = 5;
Method 3 (Declaring multiple variables simultaneously and then initializing them separately)
int a, b; a = 5; b = 10;
Method 4 (Declaring multiple variables simultaneously and then initializing them simultaneously)
int a, b; a = b = 10;
int a, b = 10, c = 20;
Method 5 (Dynamic Initialization : Value is being assigned to variable at run time.)
int a; printf("Enter the value of a"); scanf("%d", &a);
Different ways of initializing a variable in C++
Method 1 (Declaring and Initializing a variable)
int a = 5;
Method 2 (Initializing a variable using parenthesis)
int a (5) ;
Yes, they’re the same. On the other hand, for a class type they’re different. For example :
struct A { A(int); }; A a(5); // This statement is to construct a;
Method 3 (Initializing a variable using braces)
int a{5} ;
Method 4 (Declaring a variable using auto class)
auto a = 5;
‘auto (Links to an external site.)’ is a keyword which tells the compiler the type of the variable upon its initialization.
Method 5 (Declaring and Initializing a variable through ‘auto’ keyword with parenthesis)
auto a (5);
Method 6 (Declaring and Initializing a variable through ‘auto’ keyword with braces)
auto a{5};
Method 7 (Dynamic Initialization)
int a; cin>>a;
These are all the different ways in which a variable can be defined in C or C++. The ways are similar for all fundamental variable but the way to initialize a variable of derived data type changes accordingly. Different derived data types (Links to an external site.) have an altogether different way of getting their variable initialized and hence can be explored in detail while diving in the all about of that particular data type.
C++ Reference variable
C++ introduces a new kind of variable known as Reference Variable. It provides an alias (alternative name) for a previously defined variable.
A reference variable must be initialized at the time of declaration.
This establishes the correspondences between the reference and the data onject which it name.
When a reference is created, you must tell it which variable it will become an alias for. After you create the reference, whenever you use the variable, you can just treat it as though it were a regular integer variable. But when you create it, you must initialize it with another variable, whose address it will keep around behind the scenes to allow you to use it to modify that variable.
Declaration
[data_type] & [reference_variable]=[regular_variable];
regular_variable is a variable that has already initialized, and reference_variable is an alternative name (alias) to represent the variable regular_variable.
Consider the example
#include <iostream.h> int main() { int student_age=10; int &age=student_age; // reference variable cout<< " value of student_age :"<< student_age << endl; cout<< " value of age :"<< age << endl; age=age+10; cout<<"\nAFTER ADDING 10 INTO REFERENCE VARIABLE \n"; cout<< " value of student_age :"<< student_age << endl; cout<< " value of age :"<< age << endl; return 0; }
Output
value of student_age :10 value of age :10 AFTER ADDING 10 INTO REFERENCE VARIABLE value of student_age :20 value of age :20
Reference Variables as Function Parameter (Call by reference)
A Reference Variable can also be used in function parameter, this is known as call by reference.
The call by reference mechanism is useful in object oriented programming due to following reasons:
- It permits the manipulation of objects by reference.
- It eliminates the copying of object parameters.
- Reference variables can be created for user defined data types such as structures and classes.
Consider the example
//Program to illustrate call by references. #include <iostream.h> // function call by reference void fun(int &x) { x+=10; } int main() { int m=100; fun(m); cout<<"\n Value of m is : "<< m << endl; return 0; }
Output
Value of m is : 110
Difference between Pointer and Reference
- It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
- References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.