Constants - sheerazwalid/COMP-I GitHub Wiki

Constant literals

The number 16 in the following code is called a literal constant.

k = 16;

The following illustrates how to represent the number 16 using three different bases.

16        // decimal      -- base 10
020       // octal        -- base 8
0x10      // hexadecimal  -- base 16

cout << 16;   // Prints "16".
cout << 020;  // Prints "16".
cout << 0x10; // Prints "16".

WARNING: if you precede an integer literal with a zero, the compiler assumes it's an octal value. This could lead to bugs.

Representing constants with identifiers

Constants are named in 2 different ways. First, there is the old fashioned preprocessing directive from the C language.

#define PI 3.1415926
double area = PI * r * r;

Second, there is the newer C++ approach using the keyword const.

const double pi = 3.1415926;
double area = pi * r * r;

Constants defined in the preprocessing step are often in ALL CAPS.

Reading