What are constants? List and explain different types of constants with examples.
A constant is an identifier whose value remains fixed throughout the execution of the program. The constants cannot be modified in the program.
For example: 1, 3.14512, „z‟, “hello"
Different types of constants are:
- Integer Constant: An integer is a whole number without any fraction part. There are 3 types of integer constants:
- Decimal constants (0 1 2 3 4 5 6 7 8 9) For ex: 0, -9, 22
- Octal constants (0 1 2 3 4 5 6 7) For ex: 021, 077, 033
- Hexadecimal constants (0 1 2 3 4 5 6 7 8 9 A B C D E F) For ex: 0x7f, 0x2a, 0x521
- Floating Point Constant: The floating point constant is a real number. The floating point constants can be represented using 2 forms:
1 Fractional Form: A floating point number represented using fractional form has an integer part followed by a dot and a fractional part.
For ex: 0.5, -0.9
2 Scientific Notation (Exponent Form): The floating point number represented using scientific notation has three parts namely: mantissa, E and
For ex: 9.86E3 imply 9.86 x 103
- Character Constant: A symbol enclosed within a pair of single quotes(„) is called a character
Each character is associated with a unique value called an ASCII (American Standard Code for Information Interchange) code.
For ex: '9', 'a', '\n'
ASCII code of A = 65, a= 97, 0=48, etc
- String Constant: A sequence of characters enclosed within a pair of double quotes(“) is called a string
The string always ends with NULL (denoted by \0) character.
For ex: "9", "a", "sri", "\n", “”
- Escape Sequence Characters: An escape sequence character begins with a backslash and is followed by one
- A backslash (\) along with some character give special meaning and purpose for that character.
- The complete set of escape sequences are:
- \b Backspace
- \f Form feed
- \n Newline
- \r Return
- \t Horizontal tab
- \v Vertical tab
- \\ Backslash
- \' Single quotation mark
- \" Double quotation mark
- \? Question mark
- \0 Null character
- Enumeration constants: It is used to define named integer constants. It is set of named integer
Syntax for defining enumeration constants
enum identifier { enumeration-list}; // enum is a keyword Example:
- enum boolean {NO, YES};
/* This example defines enumeration boolean with two constants, NO with value 0 and YES with value 1 */
In enumeration-list, the first constant value i.e. NO is ZERO since it is not defined explicitly, and then value of next constant i.e. YES is one more than the previous constant value(YES=1).
- enum months {Jan=1, Feb, Mar, Apr, May, June,Jul,Aug,Sep,Oct,Nov,Dec};
/* This example define enumeration months with 12 constants, Jan=1,feb=2,mar=3,apr=4, ..., Dec=12 */
In enumeration-list, the first constant value i.e. Jan=1 since it is defined explicitly, and then value of next constants i.e. Feb, Mar, Apr,...,Dec are one more than the previous constant value.