Constants
Often when we write a program, we need to use the same literal value over and over. Not only is it tedious to key in the same literal over and over, but it is also prone to error. For example if you write a program that uses trigonometry functions, we would often need the value for [[π]] which is approximately 3.141592653589793. You can see how tedious it would be to type this literal value not to mention the likelihood of transposition or other errors. Having a simple named constant symbol such as PI
would make writing such a program much easier.
It is also possible that we need to use literal values in our program that change from time-to-time but not during the running of our program. Values like local sales tax rate or the [[cosmological constant]] only change infrequently so having a single place to make the required change when it is necessary helps greatly with program maintenance.
Types
In order to declare named constants or variables, we need to specifically declare what type of value they should hold. This idea is known as strong typing. By declaring the types of our symbols, it helps the compiler to detect problems that might arise from mixing different data types. The table below lists the fundamental (or intrinsic) types supported by C++.
Type | Keyword |
---|---|
Boolean | bool |
Character (ASCII Only) | char |
Wide Character | wchar_t |
8-Bit Integer | char |
16-Bit Integer | short |
32-Bit Integer | int |
64-Bit Integer | long |
32-Bit Floating Point | float |
64-Bit Floating Point | double |
String (ASCII Only) | string |
Wide String | wstring |
Void | void |
Declaration Syntax
Named constants must be initialized to a specific value when they are declared. Once initialized, they can not have their value changed during the execution of the program.
The syntax for a constant declaration consists of the keyword const
, the type of the constant, the name of the constant (see rules for identifiers), the equal sign (=
), the initializer value for the constant and ends with a semicolon (;
).
Examples of statements used to declare a named constants are illustrated below.
Questions
- What are some examples of integer constants?
- What are some examples of floating point constants?
- What are some examples of string constants?
Projects
More ★'s indicate higher difficulty level.
References
-
[[C++ Programming Language]], 4th Edition, Bjarne Stroustrup, Addison-Wesley, 2013, ISBN 978-0321563842.
- [[C++ Language Reference]]
- [[cplusplus.com]]
- [[Cprogramming.com]]