C++ Constant
In C++, a constant is a value that cannot be changed during the execution of a program. Constants are useful for defining values that should not be modified or for specifying values that are used repeatedly throughout the program.
There are two types of constants in C++:
- Literal Constants:
A literal constant is a value that is written directly in the source code of a program. For example, the following are examples of literal constants in C++:
int x = 10; // Integer literal constant float y = 3.14; // Floating-point literal constant char c = 'A'; // Character literal constant
Here, the values 10, 3.14, and 'A' are literal constants that are assigned to variables.
- Symbolic Constants:
A symbolic constant is a value that is given a name and can be used throughout the program. In C++, symbolic constants are typically defined using the "const" keyword. For example, the following is an example of a symbolic constant in C++:
const float PI = 3.14159265359; // Define a symbolic constant for pi
Here, the "const" keyword is used to define a symbolic constant named "PI" with a value of 3.14159265359. This constant can then be used throughout the program by referring to its name rather than its value.
Symbolic constants are often used to define values that are used repeatedly throughout a program, such as mathematical constants or values that are used in program configuration.
In summary, constants in C++ are values that cannot be changed during the execution of a program. There are two types of constants: literal constants, which are values that are written directly in the source code of a program, and symbolic constants, which are values that are given a name and can be used throughout the program.