Example 1: Invalid Attempt to Change a Constant Variable
#include <stdio.h>
#include <stdlib.h>
int main() {
const int x = 5;
x = 10; // ERROR! Attempting to modify a constant variable
printf("%d", x);
return 0;
}
- Error Explanation: When you declare
const int x = 5;
, it meansx
is a constant and cannot be modified. The linex = 10;
will result in a compilation error because you cannot change the value of a variable marked asconst
after it’s initialized. - This error happens because the C compiler knows that
x
is constant, and it will not allow any attempts to change its value.
Example 2: Using a Pointer to Modify the Constant (Unsafe and Undefined Behavior)
#include <stdio.h>
#include <stdlib.h>
int main() {
const int x = 5;
int* ptr = (int*)&x; // Casting away const to modify it (unsafe)
*ptr = 10; // Modifying the value through the pointer
printf("%d", x); // Undefined behavior
return 0;
}
- Explanation: In this code, you are casting away the
const
qualifier by using a pointer (int* ptr = (int*)&x;
). This lets you change the value ofx
through the pointerptr
. - Danger: This is unsafe and leads to undefined behavior because you’re violating the contract of
const
, which guarantees thatx
cannot be changed. - Even though it prints
10
, this behavior is not guaranteed and can result in unpredictable outcomes, depending on the compiler and platform.
Correct Approach:
You cannot change the value of a constant variable once it’s set. If you need a variable whose value can be changed, do not use the const
keyword. Here’s a fixed example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int x = 5;
x = 10; // This is valid since 'x' is no longer constant
printf("%d", x); // Prints 10
return 0;
}
This is the proper way to use a variable whose value can be modified after initialization.
Key Takeaway:
const
prevents modification of a variable’s value directly, and attempting to modify it (whether directly or through pointers) results in an error or undefined behavior.- If you need a variable whose value changes, avoid
const
.