Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
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.
Constants are treated just like regular variables except that their values cannot be modified after their definition.
There are two types of constants
Primary constants :− Integer, float, and character are called as Primary constants.
Secondary constants :− Array, structures, pointers, Enum, etc., called as secondary constants.
Syntax
const datatype variable;
Defining Constants:
In C/C++ program we can define constants in two ways as shown below:
- Using #define preprocessor directive
- Using a const keyword
Literals: The values assigned to each constant variables are referred to as the literals. Generally, both terms, constants and literals are used interchangeably. For eg, “const int = 5;“, is a constant expression and the value 5 is referred to as constant integer literal.
Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:
#define identifierName value
identifierName: It is the name given to constant.
value: This refers to any value assigned to identifierName.
using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword.
const float PI=3.14;
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
List of Constants in C
Constant |
Example |
Decimal Constant |
10, 20, 450 etc. |
Real or Floating-point Constant |
10.3, 20.2, 450.6 etc. |
Octal Constant |
021, 033, 046 etc. |
Hexadecimal Constant |
0x2a, 0x7b, 0xaa etc. |
Character Constant |
'a', 'b', 'x' etc. |
String Constant |
"c", "c program", "c in javatpoint"
etc. |