C constants are the variables in C language whose values can not be changed once initialized.
- Const: It is a keyword used to declare a constant variable.
- C Constants cannot change their value throughout the program.
- Constant variables have to compulsorily initialized at the time of declaration.
- Then this value cannot be changed during the entire program execution.
- Constants are also called as literals.
- Const can be applied to all data types in C language.
Syntax:
Following is a general syntax for defining a variable as constant.
1 2 3 |
const data_type constant_name = value; OR data_type const constant_name = value; |
Example:
1 2 |
const int x = 100; const float PI = 3.14f; |
From above example, we can say that x is a constant variable of integer datatype whose value doesn’t change in a program whatever will condition is. Also, PI is a constant variable of float datatype whose value 3.14f does not change during execution of the program.
Types of C constants:
C constants can be divided into two major categories. The following figure shows major types of constants in C language and then we discuss each type in detail.
Primary constants – Primary constants are furthermore divided into following three types:
- Integer Constant
- Real or Floating-point Constant
- Character Constant
Secondary Constants – Secondary Constants are furthermore divided into following categories:
Integer Constant
Integer constants are the numeric constants (constants associated with the number) without any fractional part or exponential part.
The allowable range for integer constants is -32768 to 32767 for a 16-bit compiler.
For a 32-bit compiler, the range would be even greater.
You can check the size and range of datatype on Datatype Page.
An integer constant can be a decimal, octal, or hexadecimal constant.
Example:
1 2 3 4 |
10; //int 045; //octal +782, -8000, 0X6, 0; ox4b //hexadecimal |
Real or Floating-point constant
Floating-point constants are the numeric constants that have fractional forms.
The real constants could be written in two forms—Fractional form and Exponential form.
The range of real constants expressed in exponential form is between -3.4e38 to 3.4e38.
Example:
1 2 3 4 |
+325.34 426.0 -32.76 -48.5792 |
Character Constant
Character Constants are constant which is declared inside single quotes.
The maximum length of a character constant must be 1 character.
Example:
1 2 3 4 |
'a' 'A' '2' ';' |