Lesson 6: Constant Variables

This one should be pretty short and to the point.  I just wanted to take a few minutes and discuss constant variables.

So far, we have discussed variables that could be initialized to something and then modified later.  As an example, by arithmetic operators.

In the following example, we can see that we initialize the variables “a”, “b”, and “c” to certain integers.

We then modify each of those variables to be something different, and then print them out.

What do you think the print statements will display?  Try out the code in your own IDE and let me know in the comments below.  If you want, try setting your own variables and modifying them throughout the program.


int main()
  int a = 12;
  int b = 18;
  int c = 0;

  c = a + b;
  a = c;
  b = 10;

  cout << c << endl;
  cout << a << endl;
  cout << b << endl;
  cout << a + b << endl;
  return 0;


Sometimes, we don’t want this to be able to happen.

When we want a variable to be steady throughout the program, we call that a constant.

Constants can be:

  • Literal
  • Declared

Literal constant:

In our first program, we wrote a “hello world” application.

std::cout << "hello world" << std::endl;

The “hello world” portion of this code is a string literal constant. This is created and printed at the same time and there is no way to modify it.

Declared constant variables using “const”:

Now, we can also programmatically declare a variable as a constant using the const keyword.

const int myConstantNumber = 87;

This forces the variable to remain a constant 87 no matter what.  If someone wrote some code that tried to modify this variable, there would be a compilation error at build time.

Take a break and try this for yourself.  Declare a constant variable, attempt to modify it further down in the code, and then see what happens when you try to compile.  Leave your results in the comments section below!

NOTE: declaring variables that shouldn’t change by using the “const” keyword is considered good programming practice.  This not only forces the variable to remain as is, but it also helps show other programmers that look at the code that this was purposefully done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s