Home

#5 Constants

Constants

In C++, a constant is a value that cannot be altered by the program during its execution. Constants are useful for defining values that you don’t want to change accidentally, and they make your code easier to understand and maintain.

10, 3.14, or ‘A’ are constants.  These values can be used in calculations but will never change. Not to be confused with the assignment of a constant to a variable. The variable itself can change but the literal itself will not.  

Example:

// Ex03.cpp - Constants Explained

import std;

int main()
{
	int num = {10};   	// this is the literal value 10 being assigned to variable num
	const float mypi = {3.14159f};    // the literal value 3.14159 being assigned to the constant variable mypi

	std::println("The variable num {}", num);				// 10 is printed but num can change
	num = num + 30;											// num changed
	std::println("The literal value {}", 20);               // 20 is printed but 20 will always be 20
	std::println("The constant value mypi {}",mypi);        // 3.14159 is printed and will always be 3.14159
	std::println("The variable num {}", num);               // 30 was added so 40 will print

	return 0;
}

So when do we want to use a constant and when do we want to use a variable?  

Programming should be though of in terms of the real world (in most cases).  So if we take this question and change it to where in the world are there things that cannot be altered?  We get things like the pigmentation of a specific color blue or the height of a building or length of a bridge.   These are the types of things in our programs that should be defined as constants and are more convenient to be defined as such.  The 3.14159 value that is often given as an example of a constant is great because no matter how much you argue or think or complain there is nothing you can do to change the meaning of PI, it will be now and forever, 3.14…  

So how do these constants help in programming?  Nowadays, the vast amounts of memory allow us to do things that were thought of as bad in the early days of programming were every byte of space mattered.  An example would be defining the data of a contract expiration.  If that were to be 2029 then we might put a variable in the code like this.

const int contractExp {2029};

We might use that in 100 places in the code for calculations based on days remaining, value per day till expiration, and so on.  However, if a update to the contract it made to extend it to 2033 we only need to go in and update the one location, knowing that it was not changed somewhere else by some other logic.