In C language, constants is values or variables that cannot be modified once defined. They are fixed in the program. It can be of any type like int, char float, octal, hexadecimal etc.
List of Different types of constants in C programming.
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", "protec" etc.
|
How to define constants in C?
There are two ways to define constants in C:
- By using const keyword
- By using #define preprocessor directive
1) Defining constants by using const keyword:
In C programming, the const keyword is used to define constant variable that value cannot be modified once defined.
Syntax to define constant variable:
const data_type variable_name = value;
Example 1: Declaration of constants variable of different data types
#include <stdio.h>
int main()
{
/*Constant Variables once defined cannot be changed in the program.*/
const int b=10; //Integer constant
const float PI= 3.14; //Real constant
const char ch= 'C'; //Character constant
const char arr= "Protec"; //String constant
printf("Integer constant: %d\n", b);
printf("Real constant: %.2f\n", PI);
printf("Character constatn: %c\n", ch);
printf("String constatn: %s\n", arr);
getch();
}
Output
Integer constant: 10
Real constant: 3.14
Character constant: C
String constant: Protec
Example 2: Constant variable cannot be modified once defined
#include <stdio.h>
int main()
{
/*Constant Variables once defined cannot be changed in the program.*/
const int b=10; //Integer constant
b=15; //It cannot be changed since b is already defined as constant.
printf("Integer constant: %d\n", b);
getch();
}
Output
Compile time error, cannot modify a constant object.
2) Defining constants by using #define preprocessor directive:
This directive is used to declare an alias name for existing variables or values. You can use this to declare a constant.
More on this to be updated soon...
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.