Variables vs Constants (Differences)
Key differences between variables and constants are discussed briefly :
Variables are named memory location whose value can change during program executions.
Any entity that does not change during program execution are referred to as constants. In C, we can have named memory as constant as well.
Syntax for creating variables is:
data_type variable_name = value;
Syntax for creating constant is:
const data_type constant_name = fixed_value;
Variable Example:
int num = 45;
Here value of num
can be changed during program execution.
Constant Example:
const float pi = 3.141592;
Here value of pi
cannot be changed during program execution.
Variables can be initialized after their declaration i.e.
Declaration:
Initialization:
Declaration:
float ratio;
Initialization:
ratio = 3.4;
Constants must be initialized at the time of declaration i.e.
is valid but we cannot do something like:
Declaration:
Initialization:
const float pi = 3.141592;
is valid but we cannot do something like:
Declaration:
const float pi;
Initialization:
pi = 3.4;