#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 ca开发者_如何学Gon 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.
*(float *)ptr_to_const_char = 2.18;
However, const is not useless.
- It provides documentation, a programmer reading code where a pointer is declared const can assume he can/should not modify what the pointer points to
- It can enable the compiler to do further optimizations
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.
It is indeed a fact. In fact, the compiler turns off const optimizations (few as there are) the moment it sees you casting away const
, treating it like any other variable.
const
does not protect a variable. In fact, const
does not even mean the variable will never change.
What it means is that you, the programmer, declare that you won't be writing to that part of memory. A memory-mapped input-only pin on a microchip might be represented by a variable qualified const
, but it can still change if the voltage on the pin changes. (In fact, it will most likely be declared const volatile
, which blew my mind the first time I saw it.) But the const
means that you aren't allowed to write to it.
So if you break that promise — that you have no intention of writing to it — well then yes, of course that'll mess things up.
You are programming in C and its always like that. While playing with pointers you need to be careful always.
I believe you want
char * const ptr_to_const_char
which is a constant pointer, not a pointer to a constant.
But that may only work in C++.
Modifying the content of a variable defined as const using such means is clearly UB. Avoid that.
精彩评论