Introduction
Fundamentals
C Flow Control
C Functions
C Arrays
Constants in C Language
Constants are special type of variables, whose values can't be changed during program execution. In this tutorial, we will learn about their usage, constants creation and types of them.
Constants are the fundamental and essential part of the C programming language. Constants are the fixed values that are used in a program. Their value remains the same during the entire execution of the program. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
1. Defining Constant In C Program:
In C language, the const keyword is used to declare constants. Syntax for defining constants in C is as below:
const datatype = value;
Example:
The example below shows how to declare a constant:
#include <stdio.h>
int main()
{
const float pi = 3.14; //The value of pi is set as constant
float area, r;
printf("Enter the radius of the circle : ");
scanf("%f", &r);
area = pi * r * r;
printf("\nThe area of the circle is %f", area);
return 0;
}
2. Types of Constants in C Language
In C Language, there are 5 different types of constants based on the data type they have.
1. Integer Constants
An Integer constant is an integer data type variable, having a fixed value that can't be changed throughout the program. Integer Constants can be further classified into three types:
- Decimal number system constants
- Octal number system constants
- Hexadecimal number system constants
2. Floating or Real Constants
We use a floating-point constant to represent all the real numbers which can be shown on the number line. It also includes all fractional values. Floating Constants can be represented in two ways.
- Decimal Form
- Exponential Form
3. Character Constants
Character constants are used to assign a fixed value of the character to a variable. Each character is associated with its specific numerical value, also called the ASCII value. The Full-Form of ASCII is American Standard Code For Information Interchange.
4. String Constants
A String Constant represents an array of characters that is immutable or can't be changed throughout the program. For Example: "Hello" is the example of String, which can be converted to read-only by adding a const keyword in front of its declaration.
5. Enumeration Constants
These are user-defined data types in C with a fixed value having data type that consists of integral constants. To define new enum constants, enum keyword can be used.