How to modify a const variable in C?

In C, const variables are designed to be immutable after initialization. However, there are ways to modify their values using pointers, though this practice leads to undefined behavior and should be avoided in production code.

Syntax

const data_type variable_name = value;
int *ptr = (int*)&const_variable;  // Cast away const
*ptr = new_value;  // Modify through pointer

Example 1: Attempting Direct Modification (Compile Error)

Direct assignment to a const variable results in a compilation error −

#include <stdio.h>

int main() {
    const int x = 10;
    printf("x = %d<br>", x);
    
    /* Uncomment the next line to see compile error */
    /* x = 15; */  /* Error: assignment of read-only variable 'x' */
    
    printf("Direct modification not allowed<br>");
    return 0;
}
x = 10
Direct modification not allowed

Example 2: Modifying const Variable Using Pointer

By casting away the const qualifier, we can modify the variable through a pointer −

#include <stdio.h>

int main() {
    const int x = 10;
    int *ptr;
    
    printf("Before: x = %d<br>", x);
    
    ptr = (int*)&x;  /* Cast away const */
    *ptr = 15;       /* Modify through pointer */
    
    printf("After: x = %d<br>", x);
    return 0;
}
Before: x = 10
After: 15

Key Points

  • Modifying const variables through pointers leads to undefined behavior.
  • The compiler may optimize code assuming const variables never change.
  • This technique should never be used in production code.
  • Different compilers may produce different results with such code.

Conclusion

While it's technically possible to modify const variables using pointer casting, this practice violates the const contract and results in undefined behavior. Always respect const correctness in your programs.

Updated on: 2026-03-15T10:29:54+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements