逆方向に読む (時計回り/らせんの法則による):
int*
- intへのポインタint const *
- const intへのポインタint * const
- int への const ポインターint const * const
- const intへのconstポインタ
今最初の const
タイプのどちらの側にもできるので:
const int *
==int const *
const int * const
==int const * const
本当にクレイジーになりたい場合は、次のようなことができます:
int **
- intへのポインタへのポインタint ** const
- int へのポインターへの const ポインターint * const *
- int への const ポインターへのポインターint const **
- const int へのポインタへのポインタint * const * const
- intへのconstポインタへのconstポインタ- ...
const
の意味を明確にするために :
int a = 5, b = 10, c = 15;
const int* foo; // pointer to constant int.
foo = &a; // assignment to where foo points to.
/* dummy statement*/
*foo = 6; // the value of a can´t get changed through the pointer.
foo = &b; // the pointer foo can be changed.
int *const bar = &c; // constant pointer to int
// note, you actually need to set the pointer
// here because you can't change it later ;)
*bar = 16; // the value of c can be changed through the pointer.
/* dummy statement*/
bar = &a; // not possible because bar is a constant pointer.
foo
定整数への可変ポインタです。これにより、ポイントするものを変更できますが、ポイントする値は変更できません。ほとんどの場合、これは const char
へのポインターがある C スタイルの文字列で見られます。 .指す文字列を変更することはできますが、これらの文字列の内容を変更することはできません。これは、文字列自体がプログラムのデータ セグメントにあり、変更すべきではない場合に重要です。
bar
変更可能な値への定数または固定ポインタです。これは、余分なシンタックス シュガーのない参照のようなものです。このため、通常は T* const
を使用する参照を使用します。 NULL
を許可する必要がない限り、ポインター
時計回り/らせんの法則を知らない人のために:変数の名前から始めて、時計回りに (この場合は後方に) 次の ポインタ に移動します。 またはタイプ .式が終わるまで繰り返します。
デモはこちら:
ここではすでにすべての回答が得られていると思いますが、 typedef
に注意する必要があることを付け加えたいと思います !単なるテキスト置換ではありません。
例:
typedef char *ASTRING;
const ASTRING astring;
astring
の型 char * const
です 、const char *
ではありません .これが、私が常に const
を入れる傾向がある理由の 1 つです。 タイプの右側にあり、先頭にはありません。