Const Qualifier in C
×


Const Qualifier in C

30

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:

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>

int main() {
    const int AGE = 30;
    printf("Age: %d\n", AGE);
   // AGE = 31;  // Error: Assignment to const variable
   return 0;
}	

Output:

Age: 30

2 Pointer to Constant

#include<stdio.h>

int main() {
   int num = 10;
   const int *ptr = #
   printf("Value: %d\n", *ptr);
   // *ptr = 20;  // Error: Cannot modify value
   return 0;
}	

Output:

Value: 10

3 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;
}	
Output:

Value: 10

4 Constant Pointer to Constant

#include<stdio.h>

int main() {
    int num = 10;
    const int *const ptr = #
    printf("Value: %d\n", *ptr);
    // *ptr = 20;  // Error: Cannot modify value
    return 0;
}	

Output:

Value: 10

Importance:

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.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments