Explain the declaration of variables in C++

Estudies4you
Q17. Define variable. Explain the declaration of variable.
Answer:

Variable 
A variable is the name that is assigned for referring to the memory location, where the data value (i.e., value assigned to the variable) of the variable is stored. Unlike constant, the value of a variable can be changed during execution.
A variable can be classified as integer variable, real variable, character variable depending on the type of value stored in it.
A variable name must be chosen in such a way that it improves the readability of a program and also reflects its function.

Variable Declaration
In C++, variables can be declared anywhere in the program. They can be used only after their declaration. After the declaration of variables, the compiler is informed about the data type of the variable. This makes allocation of memory easier.
The compiler then gets the variable name. Variables which are declared before the main( ) function are known as external variables. The syntax for declaring variables is as follows, data_type variable_name.

Example
int i;
Here ‘int’ is the data_type and ‘i’ is the variable_name.
Variable Initialization
Variable initialization refers to assignment of variable with value. A variable is ready to be used only after it is initialized.

Syntax
data_type variable_name=data_value;

Example
int i =4;
Here, int is the data_type.
i is variable_name.
4 is data_value.

If a variable is used before its initialization, then a garbage value is assigned to that variable. Garbage values are not static, they vary from system to system.

To Top