Constant variable definition
Constant is a value that cannot be reassigned. A constant is immutable and cannot be changed. There are some methods in different programming languages to define a constant variable. Most uses the const keyword. Using a const keyword indicates that the data is read-only. We can use the const keyword in programming languages such as C, C++, JavaScript, PHP, etc. It can be applied to declare an object. Java does not directly support the constants. The alternative way to define the constants in java is by using the non-static modifiers static and final.
The keyword const creates a read-only reference to the value. It can neither be re-declared nor can’t a value be reassigned to it. That means a const variable or its value can’t be changed in a program.
Now, let’s see how to use or declare constant in some programming languages.
C programming language
In C, we can define the constant in two ways that are by using the const keyword or by using the #define preprocessor. Now, let’s see the piece of codes to see how to define constant using both ways.
By using const keyword
Output
The value of PI is: 3.140000
In the above code, the variable PI is constant, and on trying to change its value, an error will be rendered.
By using #define preprocessor
Output
3.140000
In the above code, the variable PI is constant and defined using the #define preprocessor.
JavaScript
In JavaScript, the concept of defining the constant variable is introduced in ES6. ES6 gives us a new way to declare a constant using the const keyword. The keyword const creates a read-only reference to the value. The const is a block-scoped and cannot be re-declared. The constant must be initialized during declaration.
A const variable cannot be hoisted, which means that a variable declared/initialized using var keyword cannot be reassigned using const.
Output
The value of const variable x = 16
PHP
In PHP, there are two ways of defining a constant variable that is by using the define() function or by using the const keyword. Constants are similar to the variable except that we cannot change them. They remain constant across the program. Constants in PHP follows the rules same as the PHP variable. Now let’s see the piece of codes to see how to define a constant in PHP by using the define() function or by using the const keyword.
By using the define() function
Output
Hello World
In the above code, the msg is the constant variable name, and Hello World is its value. If we try to modify its value, an error will be rendered.
By using the const keyword
PHP introduced a const keyword to create a constant. It is a language construct, not a function. The constant defined using the const keyword is case-sensitive.
Output
Hello World