C++ has two types of constants: literal and symbolic.
The const keyword is used to create a "read only" variable.
It defines constant that cannot be modified and must be initialized during its definition.
const double pi = 3.1415947;
The value of pi cannot be modified by the program.
A statement such as the following will result in an error message:
pi = pi + 2.0; // invalid
#include <iostream> using namespace std; int main() /*from w ww. j av a 2 s . c o m*/ { const double pi = 3.1415947; cout << pi; return 0; }
A symbolic constant is a constant represented by a name, just like a variable.
The const keyword precedes the type, name, and initialization.
Here's a statement that defines a constant:
const int Score = 5000;
The preprocessor directive #define can create a constant by specifying its name and value, separated by spaces:
#define Score 5000
The constant does not have a type such as int or char.
The #define directive enables a simple text substitution that replaces every instance of Score in the code with 5000.