Constant in C
In C programming constant is a read-only variable that once defined and cannot be modified later in the code. In C language constant can be defined in two ways using #define or const keyword.
Why Use Constant?
Constant means something that never changes, In programming, there are many situations that arise when a fixed value need at many places in the entire program in such conditions C constant plays a very crucial role.
For example, suppose there is a program in which the value of Pi (3.147) is needed many times, In this condition, we know that the value of Pi is never going to change so it is safer to store the value of Pi in a constant rather than a regular variable.
Constant Declaration in C
In C programming, a constant can be declared in two ways using keywords
- #define
- const
1. Constant Declaration Using #define
In a C program, a constant can be declared using #define preprocessor, See below syntax and example.
Syntax
#define NAME Value
Where
- NAME - is the name of constant, it is user-defined.
- Value - Value is the value of constant.
Note:
- It is best practice to NAME of constant in capital letter.
- Semi column (;) is not required after 'Value'.
- The constant variable is also called Macro.
- There are many Pre-Defined Macros such as __DATE__, __TIME__, etc.
Example:
#include<stdio.h>
#define SAL 30000
void main()
{
printf("Your Salary=%d",SAL );
return 0;
}
Output
Your Salary=30000
Example Explained:
- In the above example, SAL is a constant.
- The value of SAL cannot be modified, If we try, the program will give an error.
2. Constant Declaration Using const Keyword
This is the most common and popular way of declaring a constant in C programming, In this technique, we use the const keyword to convert a variable into a constant. The const keyword is defined in stdio.h header file.
Constant Declaration Syntax
const Data-Type NAME = Value;
Where
- const - this is the keyword that converts a regular variable into a constant.
- Data-Type - The type of value you want to store in constant.
- NAME - is the name of constant, it is user-defined.
- Value - Value is the value of constant.
Example Syntax
const float PI = 3.147;
const int a=20;
const char alphabet ="a";
Example
#include<stdio.h>
int main()
{
const float PI = 3.147;
float radius = 4.7
float area = PI * (radius*radius)
printf("Total Area = %f",area );
return 0;
}
Output
Total Area = 69.517
This was all about how a constant can be declared in two ways in C programming, Let's know the type of constant in the C language.
Types of Constant in C
In C programming constants can be categorized into two broad categories.
- Numeric constants
- Character constants
1. Numeric constants
A numeric constant refers to a sequence of number digits for example 132, -532, 101.001, etc. Numeric constants further can be categorized into 4 sub-categories.
- Decimal integer
- Octal integer
- Hexadecimal integer
- Floating point or Real constant
A. Decimal Integers
Decimal integers can contain a set of number digits, 0 through 9 are called decimal integers. Decimal integers can be preceded by an optional + or – sign.
Example
321, -545, 0, 345, +8462 etc.
Note: Decimal integer does not allow embedded space, comma, and non-digit characters between number digits for example 23 421, 100,000, $13400, etc.
B. Octal Integers
An Octal Integer constant consists of any combination of digits from the set of 0 through 7, with a leading 0. Let’s take some examples of the octal integer constant.
0224, 0, 0432, 0421, etc.
C. Hexadecimal Integer
A sequence of digits preceded 0x or 0X is considered as Hexadecimal integer. They can also include alphabets a,b,c,d,e,f. The alphabet a denotes number 10, similarly b,c,d,e,f denotes the numbers 11,12,13,14,15 respectively. Below we have listed some examples of hexadecimal integer examples.
0X9a2, 0xf2a, 0xac53, 0x, 0Xacd, etc.
D. Floating Point or Real Constant
A Floating-point constant refers to a sequence of number digits including a fractional point. Floating-point constants are also called real constant because it represents real numbers. Below we have listed some floating-point constant examples.
3.531, +.7, -32.561, .521, 0.0012, etc.
2. Character constants
In C programming character constants are divided into 2 categories.
- Single character constants
- String constants
A. Single Character Constants
A Character constant refers to a single character coated within a single quotation. For example ‘a’, ‘b’, ‘m’, ‘d’, etc.
Example
const char answer='Y';
const char is_active='n';
B. String constants
A String constant refers to a group of characters coated within the double quotation. For example "my name is sam", "hello", "today is Friday" etc.
Example
const string name[50]="Kristi Jenf"
const string address[120]="H/N- 32 L17 North California USA"
Some other useful constants
1. Escape Sequences
In C programming, escape sequences are represented by \ followed by character or symbol. Escape sequences have special meanings and they can’t be used in general writing.
The list of all escape sequences is listed below with their representation and meaning.
Escape Sequence (Meanings)
- \b (Backspace)
- \f (Form feed)
- \n (Newline)
- \r (Carriage return)
- \t (Horizontal tab)
- \" (Double quote)
- \' (Single quote)
- \\ (Backslash)
- \v (Vertical tab)
- \a (Alert or bell)
- \? (Question mark)
- \N (Octal constant (N is an octal constant))
- \XN (Hexadecimal constant (N – hex.dcml cnst))
- \0 (Null character)
2. Enumeration Constants
You can also define enumeration constant by using enum keyword, see below example
const enum color{red, blue, green, yellow};
Constant Examples
Example 1:
Program to print the value of pi up to 5 decimal points.
#include<stdio.h>
#define PI 3.14159
int main()
{
printf(".5f",PI);
return 0;
}
Output
3.14159
Note: Never include (; ) with #define, it will give you an error.
Example 2:
What will be the output of the below program
#include<stdio.h>
#define myNum 98
int main()
{
int myNum = 67;
printf("%d", myNum);
return 0;
}
Output:
Error
Explanation:
Since we have already declared myNum constant in the header section and again we are declaring a variable with the same name and assigning it with a value that is technical will be like
( int 98 = 67 ) and this is meaningless.
Solution:
- You can choose the different names for variable and constant.
- OR If is good practice to write the constant name in capital letter, since C is case-sensitive so the problem will no longer exist.
Example 3:
What will be the output of the below program
#include<stdio.h>
#define ADD (x,y) x+y
int main()
{
printf("The sum of two numbers: %d", ADD(15,5));
return 0;
}
Output:
The sum of two numbers: 20
Note: You can declare constant as a function as the above constant declaration.
Example 4:
What will be the output of the below program
#include<stdio.h>
int main()
{
const int myNum = 30;
myNum = 50;
printf("The numbers is: %d", myNum);
return 0;
}
Output:
Error - Assignment of read-only variable 'myNum'
Note: A constant can be assigned only once, if you are trying to re-assign it, it will give you an error.