Variables are a very important part of programming. We define variables in order to store data in simple or complex forms. Constant is used to create a variable which value can not be changed. This may seem a bit strange but in some cases, it can be very helpful.
Constant Variable
In general constant variable definition is very similar to the normal variable definition in most of the programming languages. There are some exceptions where we will learn them below. Normally variables values may change without any restriction. But in some cases like preventing to change data or damage, we may need to protect variable content or data from outside effects and changes. The general syntax of the constant is like below.
const TYPE VARIABLE_NAME;
- `const` is the keyword which is generally used to set constant the given variable
- `TYPE` is the variable type like integer, string, character, etc.
- `VARIABLE_NAME`is the name of the variable which will be used as constant.
Constant Variable Rules
There are some rules while using constant variables.
- Constant array elements can be changed in JavaScript where new elements can be assigned or existing elements can be removed.
JavaScript Constant Variable
JavaScript programming language provides the const
keyword before the variable definition. But while defining the variable we will not use let
or var
keywords. In complex objects the object content can change one by one but can not be changed the object completely.
const age= 25; const name ="poftut.com"; const myobject = {"poftut.com",25};
C/C++ Constant Variable
C/C++ programming languages use the const
keyword in order to define constant. The variable which is defined as constant will be stored in the .rodata
segment of the application. Below we define different types of constant.
const int age = 25; const char* name[] = "poftut.com"; const long range = 1223235234;
PHP Constant Variable
PHP also provides the define()
function in order to create constant variables. PHP constant definition process is a bit different where we will provide the constant variable name and value as parameters to the define() function
define("age" , "25"); define("name" , "poftut.com");
It may seem that defined constants like age and name are both string but they are not. They are constant and do not have any type where every time they are used they will act according to usage position.
Java Constant Variable
Java programming language also provides constant variables. In order to make a variable or object constant static
and final
keyword is used. There are also other functions of the static keyword. Below we can see some constant variable examples.
static final int age=25; static final String name = "poftut.com";