Variables and Constants in C++
What is a Variable ?
A variable refers to a storage area whose contents vary during processing. For example, to store salary of a employee, we need a variable.Declaration of a Variable –
A variable name is declared bydata_type variable_namewhere data_type is the data types provided by C++ and variable_name is the identifier. Thus, the naming convention rules for naming an identifier is also applicable to name of the variable. To store salary of an employee,
int emp_salary;if more than one variable is to be defined, then variable name is separated by commas.
int day, month, year;
Symbolic Variables –
The variables are referred as symbolic variables as they are named locations or it can be said that we give a name to a location in the computer memory. There are 2 values associated with a symbolic variable –- rvalue (pronounced as r-value) – data value of variable stored at some location
- lvalue (pronounced as el-value) – location value of a variable, the memory address at which its data value is stored
lvalue of emp_salary = 1001 lvalue of character = 1006 rvalue of emp_salary = 20000 rvalue of character = d
Initialization of Variables –
If we do not give the data value of variable, then the variable is called uninitialized variable. and the variable data valuse is said to be undefined. Static Initialization – A variable is initialized by declaring/assigning its rvalue. C++ supports two forms of variable initialization at the time of variable definition :int val = 100; (or) int val(100) ;Dynamic (or) Run Time Initialization – If the initialization of variable is done at run time. A variable can be initialized at run time using expressions at the place of declaration. For instance,
float avg = sum/count ;
Constants –
As said earlier, a constant never change their value during a program run. Access Type : Read only. How to create a constant? const keyword is required to create a constant. For exampleconst int c=100 ; (or) const c=100 ;If the data type is not declared in initialization of constant, then automatically it is said to be an integer constant.
Difference Between Variables and Constants in c++
| Basis | Variables | Constants |
| Definition | A variable is a named location, whose value changes during a program run | A constant is a named location, whose value never changes during a program run. |
| Syntax | data_type variable_name | const data_type variable_name= value |
| Example | int a; | const int a=100; |
| Static Initialization | Variables can be initialize after its declaration also. | constants must be initialized at the time of decelaration only. |
| Dynamic Initialization | Variables can be initialize dynamically | Dynamic Initialization of constant is not possible. |