Initialized variables vs named constants

variables

I'm working on a fundamental programming class in college and our textbook is "programming logic and design" by joyce farrell(spelling?)

Anyhow, I'm struggling conceptually when it comes to initialized variables and named constants.

Our class is focusing on pseudo-code for the time being and not one particular language so let me illustrate what I'm talking about.

Let's say I am declaring a variable named "myVar" and the data type is numeric:

num myVar

now I want to initialize it (I don't understand this concept) starting with the number 5

num myVar = 5

how is that any different than creating a named constant?

Best Answer

The initialization process may look the same, but a constant cannot be changed once it is set. Depending on the type of variable (private, protected, public), other things, such as the current class, subclasses, or other classes, can act on and may have the ability to change the value of that variable. A constant stays the same for all things using it.

So lets say you initialize a variable to say:

var normalVariable = 10;

Later in your code you could change it to 20, or something, if you wanted. With a constant (which is usually named in all caps LIKE_THIS), you couldn't change the value to something else, you would most likely get an error if you tried.

For the most part, a variable is what it claims to be. It is something that may not always be a certain value. A constant on the other hand would be something that you want to signify as something that will not change. Think gravity or Pi in the real world.

Related Topic