Pointers/Memory Allocation   «Prev  Next»
Lesson 2 The const keyword
Objective Examine the use of the keyword const.

C++ const Keyword

As we saw in a previous module, the keyword const is a type specifier. When used alone in a declaration, the base type is implicitly int. A variable declared as const cannot have its value changed. A const variable can be used in places that otherwise would require a literal, such as an array size.

const and lvalue

When an ordinary variable is used on the left side of an assignment, it is used as an lvalue. An lvalue is an expression that can be used as an address to be stored into. A const variable cannot be used on the left side of an assignment. It is a nonmodifiable lvalue. This implies that a const variable must be initialized where defined.

Specifying Integer Constants

Because you can have different types of integer variables, you might expect to have different kinds of integer constants. If you just write the integer value 100, for example, this will be of type int. If you want to make sure it is of type long, you must append an uppercase or lowercase letter L to the numeric value. So 100 as a long value is written as
100L.
Although it is perfectly legal to use it, a lowercase letter l is best avoided because it is easily confused with the digit 1. To declare and initialize the variable Big_Number, you could write this:
long Big_Number = 1287600L;

You write negative integer constants with a minus sign, for example:
int decrease = -4;
long below_sea_level = -100000L;
You specify integer constants to be of type long long by appending two Ls:
long long really_big_number = 123456789LL;

To specify a constant to be of an unsigned type, you append a U, as in these examples:
unsigned int count = 100U;
unsigned long value = 999999999UL;
To store integers with the largest magnitude, you could define a variable like this:
unsigned long long metersPerLightYear = 9460730472580800ULL;
The ULL specifies that the initial value is type unsigned long long.