Constants, as the name suggests, are fixed values. In programming, the values of constants cannot change during execution.
There are two main kinds of constants:
Literal constants are values fixed in the source code. For example, in print("Hello World!")
, “Hello World!” is a string literal.
Defined constants, however, are constants defined with names. For example, Avogadro’s constant or the value of Pi are defined constants. When defining such constants, the constant’s name needs to be in all caps.
The code below shows how defined constants can be used in C++, Python, and Java:
#include <iostream>using namespace std;// Constants in C++ can either be defined like this:#define LENGTH 5#define WIDTH 2#define NEWLINE '\n'int main() {// Or be defined using the const keyword as below:const double PI = 3.14159;cout << PI << endl;cout << LENGTH << endl;cout << NEWLINE << endl;cout << WIDTH << endl;}
In the code above, try to redefine constants in Java and C++. You will notice that an error shows up. This is because, in Python, changing the value is allowed, but it is a bad programming practice to do so.
Variables, on the other hand, are values that can change as the program executes.
Since variables are more widely used than constants, no keywords are needed to indicate if a value is a variable. The code below shows this in C++, Python, and Java:
#include <iostream>using namespace std;int main() {int x = 7;double y = 2.4;char z = 'e';cout << x << endl;cout << y << endl;cout << z << endl;}