In this tutorial, you will learn about C constants and how to create them in C Programming.
Constants are the same as variables except they cannot be changed once defined.
C constants are one of the most fundamental and essential parts of the C programming language. Constants in C are the same as variables but the values are fixed, and its value remains the same during the entire execution of the program.
- Constants can be any of the data types.
- Constants are also called literals.
- The best practice in C language is to define constants in upper-case characters.
Defining a C constant
There are two ways to define a constant in the C language.
- const keyword
- #define preprocessor
1) Defining C constant using const keyword
Syntax
const type constant_name;
Example
#include<stdio.h> int main(){ const float PI=3.14; printf("The value of PI is: %f",PI); return 0; }
Program output
The value of PI is: 3.140000
Putting const
either before or after the data type is possible.
const float PI = 3.14;
or
float const PI = 3.14;
If you try to change the value of PI
, it will give the compile-time error.
#include<stdio.h> int main(){ const float PI=3.14; PI=4.5; printf("The value of PI is: %f",PI); return 0; }
Program output
Compile Time Error: Cannot modify a const object
2) Defining C constant using #define preprocessor
The #define preprocessor is also used to define constant. We will learn about the #define preprocessor directive in the later chapter.
Types of C constant
Constant | Example |
Integer Constant | 10, 20, 30, 250 etc. |
Real or Floating-point Constant | 11.5, 22.4, 250.3 etc. |
Octal Constant | 036, 012, 045 etc. |
Hexadecimal Constant | 0x3a, 0x5b, 0xbb etc. |
Character Constant | ‘a’, ‘b’, ‘x’ etc. |
String Constant | “c”, “c tutorial”, “c in tutorialsbook” etc. |