定数整数ポインタの値をbで変更することができます。 は、誤って値を変更/制限することはできますか?理解関数(const int * a)整数定数へのポインタ
#include <stdio.h>
/**
* Snippet to under working of "pointer to integer(any) constant"
*
* We are able to modify the value of constant integer pointer by b, how
* can we make sure/restrict accidentally modification of the value .
*
*/
void modify_value(const int *m, const int *n) {
//*m = 50; // expected error, assignment of read-only location
*((int*)n) = 100; // value of pointed by pointer gets updated !!
}
int main() {
int a=5,b=10;
printf("a : %d , b : %d \n", a,b);
modify_value(&a,&b);
printf("a : %d , b : %d \n", a,b);
return 0;
}
'const'をキャストしないでください。これに関する警告が必要な場合は、例えばGCCに '-Wcast-qual'があります。 – Ryan
@ Ryan、私は一度const int *を渡すと思っていましたが、コンパイラは、指された値を修正することはできません。 プロダクションコードでconst値を明示的に変更しようとしても、これを完全に防ぐことができないのだろうかと思います。 – CrazyToExpplore
つまり、 '-Werror = cast-qual'を使うことができます...? – Ryan