C++: Variables and Constants

Variables and Constants

This C++ console lesson gives an introduction to using variables and constants. We can think of a variable as an empty box, which we can fill with a particular type of item. In the case of a variable, we can keep replacing the item. However, in the case of a constant we can only fill the box once and then leave it as it is.

Here, we declare an int type variable in the first line and then assign it the value of 4 in the second line. The first line is called a variable declaration. The "=" is called the assignment operator.

We can also initialize a variable with a value when we declare it, like this:

Otherwise, we can do it like this:

In the case of variables, we can reassign a variables value as many times as we wish.

Here, we declare the variable, assign it the value 2, and then assign it the value 3.

The variables above had type int, which stands for integer. A variable of type int cannot have a fractional part like 3.4. Instead, to hold values with fractional parts, we use a double type variable like this:

Notice that we preceded the "X" with a small "d." In this case, the "d" stands for double and tells the type of the variable. In the earlier examples, we used an "i" for int. Using small letters at the beginning of the variable name to describe the variable type is called Hungarian notation and is considered good coding practice.

Finally, we remark that we can have constants whose vales cannot be changed after they are declared. So, we must initialize them at the declaration.

Typically, we will use constants for values that we know we will not want changed. Making such values constants enforces the fixed value and makes the code less prone to errors. Use constants wherever possible. Incidentally, the "k" that we used above stands for constant, in Hungarian notation, because the "c" is already taken for something else.