Example of Constants in C
C
// C program to illustrate constant variable definition #include <stdio.h> int main() { // defining integer constant using const keyword const int int_const = 25; // defining character constant using const keyword const char char_const = 'A' ; // defining float constant using const keyword const float float_const = 15.66; printf ( "Printing value of Integer Constant: %d\n" , int_const); printf ( "Printing value of Character Constant: %c\n" , char_const); printf ( "Printing value of Float Constant: %f" , float_const); return 0; } |
Printing value of Integer Constant: 25 Printing value of Character Constant: A Printing value of Float Constant: 15.660000
One thing to note here is that we have to initialize the constant variables at declaration. Otherwise, the variable will store some garbage value and we won’t be able to change it. The following image describes examples of incorrect and correct variable definitions.
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are declared in the C program. The type of constant can be an integer constant, a floating pointer constant, a string constant, or a character constant. In C language, the const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants in C, types of constants in C, their properties and the difference between literals and constants.