In C++, the symbolic constant can be declared in the following two ways:
- Using #define
- Using const keyword
The #define Directive
The “define” is a preprocessor directive that is used to define a constant identifier known as constant macro. A constant macro is an identifier, which is assigned a particular constant value. Like other preprocessor directives, the ‘define’ directive is also used at the beginning of the C/C++ program.
The general syntax of ‘define’ directive is as follows:
#define identifier expression
Where
identifier | It indicates constant identifier name. This name can’t be used again in program (i.e as function name or variable). |
expression | It indicates constant value for the identifier that may be a string or arithmetic expression. |
For example, to assign value 3.1417 to PI, the statement will be as:
#define PI 3.1417
The const Keyword
In C++, the “const” keyword is used to declare constant identifier in a similar way as variable declared except that const keyword is used to specify a constant identifier. At the time of declaration, a value must be assigned to it. Once a value is assigned, then this value can’t be changed during the program execution.
For example, to declare a variable PI and to assign value 3.1417 by using const keyword, the statement will be as:
const float PI = 3.1417
Difference Between Define and Const
The following is the main difference between #define directive and const qualifier.
#define | const |
---|---|
It’s not terminated with semicolon “;” | It is terminated with semicolon. |
It is used as preprocessor directive. | It is used as a statement. |
Data type of constant identifier is not specified. | Data type of constant identifier is specified. |