Declaring a Variable as Constant in C

In C, you can use the const keyword to declare a variable as constant. Once a variable is declared as constant, its value cannot be changed throughout the program. This feature is useful for defining values that are intended to remain the same during program execution, ensuring that they are not accidentally modified.

Syntax for Declaring a Constant Variable


const data_type variable_name = value;
Here:

Benefits of Using Constant Variables

1: Declaring a Constant Variable


#include <stdio.h>
int main() {
    const int MAX_VALUE = 100;
    // MAX_VALUE = 200; // Uncommenting this line will cause an error
    printf("Maximum Value: %dn", MAX_VALUE);
    return 0;
}

Output

Maximum Value: 100

Explanation of the Code

In the above example:

Practical Use Cases of Constant Variables

2: Using Constants for Array Sizes

Using constants for array sizes ensures that the array length remains fixed throughout the program:


#include <stdio.h>
int main() {
    const int ARRAY_SIZE = 5;
    int numbers[ARRAY_SIZE] = {10, 20, 30, 40, 50};
    printf("Elements of the array:n");
    for (int i = 0; i < ARRAY_SIZE; i++) {
        printf("%d ", numbers[i]);
    }
    return 0;
}

Output

Elements of the array: 10 20 30 40 50

Points to Remember

Difference Between #define and const

Aspect #define Directive const Keyword
Type Checking No type checking Type checking is enforced
Memory Usage No memory allocation Memory is allocated for the variable
Scope Global (available throughout the file) Block scope (depends on where it is declared)
Modifiability Can be redefined (not recommended) Cannot be modified after initialization

Declaring variables as constants using the const keyword is a powerful way to protect critical values in your program from being altered. It enhances the reliability and maintainability of your code, especially in larger projects. Knowing when to use const versus #define directives can help you write more robust and error-free programs.