![]() |
VOOZH | about |
There are many different ways to make the variable as constant in C. Some of the popular ones are:
The const keyword specifies that a variable or object value is constant and can't be modified at the compilation time.
const data_type variable_name = initial_value;
The below example demonstrates use of the const keyword.
It will throw as error like:
error: assignment of read-only variable ‘num’
We can also use Macros to define constant, but there is a catch. Since Macros are handled by the pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences of 'var' with the literal 5) not by the compiler. Hence it wouldn't be recommended because Macros doesn't carry type checking information and also prone to error. In fact not quite constant as 'var' can be redefined like this.
#define name valueThe below example demonstrates use of macros (#define).
5 10
Note:preprocessor and enum only works as a literal constant and integers constant respectively. Hence they only define the symbolic name of constant. Therefore if you need a constant variable with a specific memory address use either 'const' or 'constexpr' according to the requirement.
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.
The below example demonstrates use of the enum keyword.
The value of var: 42
Note: The data types of enum are of course limited as we can see in above example.