Course contentsShow
← C
Lesson 499 of 1,2197. PointersFree lesson

Casting away `const` volatility

Casting away const volatility

What you'll learn: How to use type casting to temporarily bypass const restrictions and why doing so is a dangerous "emergency-only" maneuver.

The Lockbox Analogy

Imagine you are handed a glass lockbox containing a document. You are told you have "read-only" access. In C, marking a pointer as const is like putting that data behind glass. You can see it, but the compiler will stop you if you try to take a pen and edit the text.

However, C provides a "hammer" called a type cast. By casting a const pointer back into a regular pointer, you are essentially breaking the glass to reach the document. While the language allows this, it is considered volatile because if the original data was stored in a "permanent" part of the computer's memory, the program will crash the moment you try to write to it.

Forcing a Change

To "cast away" constness, you tell the compiler: "I know this was marked as constant, but treat it as a regular, modifiable variable for just a moment." We do this by placing the desired pointer type in parentheses, like (int *).

#include <stdio.h>

int main() {
    int secret_number = 42;
    const int *ptr = &secret_number; // The pointer says "don't touch"

    // *ptr = 100; // This would cause a compiler error!

    // Casting away const: "Break the glass"
    int *modifiable_ptr = (int *)ptr; 
    
    *modifiable_ptr = 100; // This works because we stripped the const label

    printf("The new value is: %d", secret_number);
    return 0;
}

The Danger Zone

You might wonder: "If I can just cast it away, why use const at all?"

The danger lies in Undefined Behavior. If the variable was originally declared as const int x = 10;, the computer might store it in a read-only hardware segment. If you cast away that const and try to change it, the program might crash, corrupt other data, or simply do nothing at all.

Casting away const is usually a last resort when working with old code libraries that weren't written with const in mind. In your own code, if you find yourself breaking the glass often, it’s a sign that your program's design needs a rethink.

Key takeaway

Casting away const lets you modify "read-only" data by stripping its protection, but it can lead to crashes if the underlying data was never meant to be changed.