Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain the constant type qualifier in C language
Type qualifiers add special attributes to existing datatypes in C programming language. The const type qualifier is used to make variables read-only, preventing their modification after initialization.
There are three type qualifiers in C language and constant type qualifier is explained below −
Const Type Qualifier
The const qualifier creates read-only variables that cannot be modified after initialization. There are three types of constants in C programming −
- Literal constants − Unnamed constants used directly in code
-
Defined constants − Named constants using preprocessor
#define -
Memory constants − Variables declared with
constqualifier
Syntax
const data_type variable_name = value;
Types of Constants
Literal Constants
These are unnamed constants that are used to specify data directly −
#include <stdio.h>
int main() {
int a = 5;
int b = 7;
int result = a + b + 10; // Here '10' is a literal constant
printf("Result: %d<br>", result);
return 0;
}
Result: 22
Defined Constants
These constants use the preprocessor directive #define −
#include <stdio.h>
#define PI 3.1415
int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("Area of circle: %.2f<br>", area);
return 0;
}
Area of circle: 78.54
Memory Constants
These constants use the const qualifier, which indicates that the data cannot be changed after initialization −
#include <stdio.h>
int main() {
const float pi = 3.1415;
const int max_value = 100;
printf("Value of pi: %.4f<br>", pi);
printf("Maximum value: %d<br>", max_value);
// pi = 3.14; // This would cause compilation error
return 0;
}
Value of pi: 3.1415 Maximum value: 100
Complete Example
Following is a comprehensive C program demonstrating all three types of constants −
#include <stdio.h>
#define PI 3.1415
int main() {
const float cpi = 3.14;
printf("Literal constant = %.2f<br>", 3.14);
printf("Defined constant = %.4f<br>", PI);
printf("Memory constant = %.2f<br>", cpi);
return 0;
}
Literal constant = 3.14 Defined constant = 3.1415 Memory constant = 3.14
Key Points
-
constvariables must be initialized at declaration time - Attempting to modify a
constvariable results in a compilation error -
constprovides type safety and helps prevent accidental modifications
Conclusion
The const type qualifier is essential for creating read-only variables in C. It enhances code safety by preventing accidental modifications and clearly communicates the intent that certain values should remain unchanged throughout program execution.
