A Constant is a data storage location used by our program like a variable. But we can't change the value of a constant during execution. There are two types of constants in C. They are
#define PI 3.14
This means that 3.14 value is assigned to a constant PI.
Note:The #define doesn't have a semicolon at the end.
This #define can be written anywhere in the program, but they can be accessed only for the portion below their declaration.
- Literal Constants.
- Symbolic Constants.
Literal Constant:
A literal constant is a value that is typed directly into the source code.
Ex:
int count=20;
A literal constant can be of an integer type or a floating-point. They differ in their representation. If we write the number as 20, it is integer notation. If we write the number as 20.05, it is a floating-point value and we use float data type to store such a value. The decimal point causes the C compiler to treat the constant as a double-precision value.
Floating point numbers can also be represented in the form of Scientific notation. Generally Scientific notation is used to write extremely large values or extremely low values.
For example,
1.23E2 represents 1.23 times 10 to the power of 2 i.e., 123.
We can also use 'e' in place of 'E'.
Similarly integers are also represented in three notations.
- Normal number i.e., 123( Base 10 System) - They have values from 0 to 9.
- Octal number i.e., 012( Base 8 system) - They have values from 0 to 7.
- Hexadecimal numbers i.e., 1A(Base 16 System) - They have values 0 to 9 and from A to F.
Symbolic Constants:
A symbolic constant is a constant that is represented by a name in the program. The value of the symbolic constant is entered only once, when it is first defined. These constants are generally written at the top of the program.
There are two methods for defining symbolic constant.
- #define directive
- const keyword.
#define keyword:
It is used as follows.
#define CONSTNAME literalFor example,
#define PI 3.14
This means that 3.14 value is assigned to a constant PI.
Note:The #define doesn't have a semicolon at the end.
This #define can be written anywhere in the program, but they can be accessed only for the portion below their declaration.
const keyword:
const is a modifier that can be applied to any variable declaration. On declaring a variable to be a constant, we are specifying that it can't be modified during the program execution. And the variable is assigned a value during its declaration only and can't be changed later.