There are many different ways to make the variable as constant
-
Using const keyword: The const keyword specifies that a variable or object value is constant and can’t be modified at the compilation time.
// C program to demonstrate const specifier#include <stdio.h>intmain(){constintnum = 1;num = 5;// Modifying the valuereturn0;}chevron_rightfilter_noneIt will throw as error like: error: assignment of read-only variable ‘num’
-
Using enum keyword: Enumeration (or enum) is a user defined data type in C and C++. It is mainly used to assign names to integral constants, that make a program easy to read and maintain.
// In C and C++ internally the default// type of 'var' is intenumVARS { var = 42 };// In C++ 11 (can have any integral type):enum: type { var = 42; }// where mytype = int, char, long etc.// but it can't be float, double or// user defined data type.chevron_rightfilter_noneNote: The data types of enum are of course limited as we can see in above example.
- Using constexpr keyword: Using constexpr in C++(not in C) can be used to declare variable as a guaranteed constant. But it would fail to compile if its initializer isn’t a constant expression.
#include <iostream>intmain(){intvar = 5;constexprintk = var;std::cout << k;return0;}chevron_rightfilter_noneAbove program will throw an error i.e.,
error: the value of ‘var’ is not usable in a constant expression
because the variable ‘var’ in not constant expression. Hence in order to make it as constant, we have to declare the variable ‘var’ with const keyword.
- Using Macros: We can also use Macros to define constant, but there is a catch,
#define var 5

