#include<stdio.h>
int main()
{
const char const_cvar1 = 'X';
const char* ptr_to_const_char = &const_cvar1;
// Simply a typecast of "ptr to a const char" to a "ptr to char" disables security !!!
*(char *)ptr_to_const_char = 'S';
printf("\n Value of const char changed from X to : %c \n", const_cvar1);
return 0;
}
Outputs:-
Value of const char changed from X to : S
I wonder if we can never rely on the const qualifier in C ? is it the fact ?
It’s C. You can do a lot of things that are stupid, causes undefined behavior, is compiler/platform dependent etc.
casting away the const modifier is one of them. You are able to do so, but you get little guarantees as to what the result will be.
You could even cast it to just about anything, at your own risk.
However, const is not useless.
can assume he can/should not modify what the pointer points to
Just keep in mind that C does not protect you against yourself or others, it also gives you the ability to not honor the type system.