C plus plus Variable

C++ Variable

C++ variable is a memory location which is used to store a value. A variable is a symbol that represents a storage location. In the computer’s memory. The information that is stored in the location is called the value of variable. All variables must be declared before they can be used. We can change value of variable during program execution.

Declaration of C++ variable

This is true with C++ as well. However, there is a significant difference between C program. C requires all the variables to be defined at the beginning of a scope.
When we read a C program, we usually come across a grow of variable declarations at the beginning of each scope level. Their actual use appears elsewhere in the scope, Sometimes for away from the place of declaration. Before using a variable, we should go back to the beginning of the program to see with it has been declared and if so if, of what type it is.

C++ allows the declaration of a variable in the scope. This means that a variable can be declared right at the place of it’s first use. This makes the program much easier to write an deduces the errors that may be caused by heaving to scan back and forth. It also makes the program easier to understand because the variables are declared in the contact of their use.
Declaration of C++ variables example:

Void main()
Float X;//declaration
Float sum =0;
For (int i= 1; i <5;i++)//declaration
Cin>> x;
Float average;//declaration

The only disadvantage of this style of declaration is that we cannot see at a glance all the variables used in a scope.

Initialization of C++ Variable

When declaring a local variable, its value is undetermined by default. But you may want a variable to store a concrete value the moment that it is declared. In other to that you have to append and equal sign followed by the value wanted to the variable declaration.

Type identifier= initial_value;
For Example, if we want to declare an int variable “a” that contains the value 0 at the moment in which it is declared, we could write Int a=0;
Additionally C ++ has a new way to initialize a variable by enclosing the initial value between parenthesis 0:
Type identifier (initial_value);
For example : In a(0); Both ways i. e int a=0 and int a (0) are valid and equivalent in C ++.

Leave a Reply

Your email address will not be published.