Const Qualifier in C
0 997
The const qualifier in C is used to declare variables as read-only, ensuring that their values remain constant throughout the program's execution.
This enhances code readability, data integrity, and program correctness by preventing unintended modifications to constant values.
Diagram:

Syntax:
Types of const: 1Constant Variables 2Pointer to Constant 3Constant Pointer 4Constant Pointer to Constant Examples: 1 Constant Variable
Output:
const data_type variable_name = value;data_type: The type of the constant variable. variable_name: Name of the constant variable. value: Initial value assigned to the constant.
Types of const: 1Constant Variables 2Pointer to Constant 3Constant Pointer 4Constant Pointer to Constant Examples: 1 Constant Variable
#include<stdio.h>Output:int main() { const int AGE = 30; printf("Age: %d\n", AGE); // AGE = 31; // Error: Assignment to const variable return 0; }
Age: 302 Pointer to Constant
#include<stdio.h>Output:int main() { int num = 10; const int *ptr = # printf("Value: %d\n", *ptr); // *ptr = 20; // Error: Cannot modify value return 0; }
Value: 103 Constant Pointer
#include<stdio.h>int main() { int num = 10; int *const ptr = # printf("Value before: %d\n", *ptr); *ptr = 20; printf("Value after: %d\n", *ptr); return 0; }
Value: 104 Constant Pointer to Constant
#include<stdio.h>Output:int main() { int num = 10; const int *const ptr = # printf("Value: %d\n", *ptr); // *ptr = 20; // Error: Cannot modify value return 0; }
Value: 10Importance: Readability: Clearly indicates that a variable's value should not change. Safety: Prevents accidental modifications to critical data, enhancing program robustness. Optimization: Enables compilers to perform optimizations knowing the variable is constant.
Share:




Comments
Waiting for your comments