Blog Tech Developer’s Guide to C++ Constant Variables

Developer’s Guide to C++ Constant Variables

Wouldn’t it be nice if we could dictate what stays constant in our lives? The C++ programming language allows us to do just that!

In C++, the developer has discretion to declare certain pieces of code constant. After a brief introduction to variables, we’ll dive into constant variables in C++, including how they’re used and their impact on the rest of a program.

Variables and Constant Variables

If you’re a student of C++, you know that a variable represents a memory location at which a value is stored. From another standpoint, a variable is assigned a value that a user, program, or programmer can modify. Each variable must be of a certain data type.

 “constant variable” is an oxymoron, they’re referred to simply as “constants” by programmers. Constants serve an important purpose in C++.

Normally, you can rewrite a variable in C++ at any time by reassigning a value to them at a later point in the code. Check out this example:

...
int passport = 587429483;
passport = 825379357;
cout << "Your passport number is " << passport;
...

Though we declared passport to be 587429483, assigning a different value to that variable replaces the number that was initially in that memory location. When we output passport in this example, we don’t return the first value but rather the second:

Your passport number is 825379357

In most countries across the world, an individual’s passport number is constant for as long as the passport is valid. If we were creating a program in C++ to document passport values, we certainly wouldn’t want those numbers overridden.

This is where constant variables come into play. Once declared, a constant variable in C++ cannot be changed elsewhere in the program. Constant variables will keep whatever value is in the memory location they represent.

The Const Keyword

To make a variable constant in C++, you need to use the const keyword. Placing this keyword in front of your variable declaration marks the variable as a constant and tells the program not to let the programmer change the value in any way. Using const in C++ looks like this:

const int passport = 587429483;

Why Use a Constant Variable in C++?

We know that the const keyword tells a C++ program the variable is special, so attempting to change it should result in an error. In addition to passport numbers, constant variables work well for adding constants to code. Here’s an example involving the speed of light:

const int speed_of_light = 186282; // Miles per second

We can now use speed_of_light in calculations for E=mc2 or other equations without worrying about the value changing.

From a programming standpoint, a constant variable tells anyone looking at the code that it contains values that should not be tampered with. This makes for clearer written code and ultimately a more streamlined approach.

Tips For Using the “const” Keyword

Upon declaring a constant variable, you’re required to assign that variable a value. You will not be able to assign this type of variable a value following declaration. The following code in C++ does not work:

...
const int passport;
passport = 587429483;
...

Because we failed to assign passport a value upon declaration, the program returns a couple of compiler errors:

const int speed_of_light = 186282; // Miles per second

We can now use speed_of_light in calculations for E=mc2 or other equations without worrying about the value changing.

From a programming standpoint, a constant variable tells anyone looking at the code that it contains values that should not be tampered with. This makes for clearer written code and ultimately a more streamlined approach.

Tips For Using the “const” Keyword

Upon declaring a constant variable, you’re required to assign that variable a value. You will not be able to assign this type of variable a value following declaration. The following code in C++ does not work:

main.cpp:16:11: error: uninitialized const 'passport' [-fpermissive]
 const int passport;
           ^~~~~~~~
main.cpp:17:12: error: assignment of read-only variable 'passport'
 passport = 587429483;
            ^~~~~~~~~

Also, you can place the const keyword either in front of or behind the declared data type:

const int passport1 = 587429483;
int const passport2 = 479546845;

Either one of these statements sets the value as a constant. Const will apply itself to the code that’s on its immediate left, unless there’s nothing there. In this case, const will apply to the code that follows to the immediate right.

Changing a Const Variable in Code

We’ve talked about const in C++ for a bit now, but what happens if we declare a constant variable and then try to change it in the code?

In the following example, we assign a passport number as a constant variable and then try to increment it up a number:

...
const int passport = 587429483;
cout << "Your passport number is " << passport;
passport++;
...

Doing so results in a compiler error telling the programmer that such a move is not possible:

main.cpp:18:13: error: increment of read-only variable 'passport'
     passport++;
             ^~

Other Ways To Use Const in C++

Believe it or not, you can use the const keyword for more than just variables. The keyword can serve a similar purpose for pointers and functions as well.

Const Pointers

To use a pointer to point to a constant variable in your code, you would employ a constant pointer. You can use a constant pointer to point to a non-constant variable, but the opposite is not valid.

Here’s what it looks like when we point at a constant variable:

...
int main()
{
    
    const int passport = 587429483;
    const int* ptr{ &passport }; // We're declaring a constant pointer to point to a constant variable

    cout << "Your passport number is " << passport << endl;
    cout << "The passport number is stored at memory location " << ptr;

    return 0;
}

Since we’ve made our pointer ptr a constant, the code compiles and runs. We see the following output:

Your passport number is 587429483
The passport number is stored at memory location 0x7fff18b05364

nterestingly, although ptr is constant, it’s possible to point it to a different variable (in a different memory location) later in your code. See the example below:

...
int main()
{
    
    const int passport = 587429483;
    const int passport2 = 368347525;
    const int* ptr{ &passport };

    cout << "Your passport number is " << passport << endl;
    cout << "The passport number is stored at memory location " << ptr << endl;
    
    ptr = &passport2;
    cout << "We can change the pointer location to " << ptr;

    return 0;
}

By adding another passport number, we can simply reassign our pointer to a new location.

Your passport number is 587429483
The passport number is stored at memory location 0x7ffd70475320
We can change the pointer location to 0x7ffd70475324

With our constant pointer, we can see the location of both our constants.

Const Member Functions

When using classes from functions you’ve created in C++, you can make those functions constant as well. It goes without saying that any function designated a constant cannot be changed once declared.

Here, we make a function constant so it’s not possible to alter the information within:

...
class Passport_Value {
    int passport;
 
public:
    Passport_Value(int p = 0) { passport = p; }
    int getPassport() const { return passport; }
};
 
int main()
{
    const Passport_Value p1(587429483);
    cout << "Your passport number is " << p1.getPassport();
    return 0;
}

We still get our standard output for this program:

Your passport number is 587429483

But we now have a protected function that we can use knowing that it’ll stay unchanged.

Learn C++ Online With Udacity

Learning to use the const keyword can save a lot of headache when writing code in C++. This keyword protects your variables, pointers, and functions from even your own hand in future lines of code. 

Itching to continue sharpening your C++ skills? 

Udacity’s C++ Nanodegree program takes you through five real-world projects and leaves you ready for the job market.

Enroll in our C++ Nanodegree program today!

Complete Code Examples

Example 1: Trying to increment a constant variable

#include <iostream>

using namespace std;

int main()
{

    const int passport = 587429483;
    cout << "Your passport number is " << passport;
    passport++;

    return 0;
}


Example 2: Pointing to a constant variable

#include <iostream>

using namespace std;

int main()
{
    
    const int passport = 587429483;
    const int* ptr{ &passport }; // We're declaring a constant pointer to point to a constant variable

    cout << "Your passport number is " << passport << endl;
    cout << "The passport number is stored at memory location " << ptr;

    return 0;
}

Example 3: Changing what a constant pointer points to

#include <iostream>

using namespace std;

int main()
{
    
    const int passport = 587429483;
    const int passport2 = 368347525;
    const int* ptr{ &passport };

    cout << "Your passport number is " << passport << endl;
    cout << "The passport number is stored at memory location " << ptr << endl;
    
    ptr = &passport2;
    cout << "We can change the pointer location to " << ptr;

    return 0;
}

Example 4: Constant Member Function

#include <iostream>
using namespace std;
 
class Passport_Value {
    int passport;
 
public:
    Passport_Value(int p = 0) { passport = p; }
 
    int getPassport() const { return passport; }
};
 
int main()
{
    Passport_Value p1(587429483);
    cout << "Your passport number is " << p1.getPassport();
    return 0;
}

Stay updated on the latest in technology

"*" indicates required fields

Stay updated on the Latest in Tech

Be first to hear about special offers, news, and resources from Udacity

"*" indicates required fields