const int *
、、const int * const
およびを正しく使用する方法をいつも間違えてしまいますint * const
。何ができて何ができないかを定義する一連のルールはありますか?
割り当て、関数への受け渡しなどに関して、すべきこととすべきでないことをすべて知りたいです。
ベストアンサー1
逆から読んでください(時計回り/螺旋ルール):
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
- const ポインタから int ポインタへの const ポインタ- ...
不安な場合は、次のようなツールを使うことができます。cdecl+宣言文を自動的に散文に変換します。
の意味を明確にするために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
は定数整数への変数ポインタです。これにより、指し示す対象を変更できますが、指し示す値は変更できません。これは、 へのポインタを持つ C スタイルの文字列で最もよく見られますconst char
。指し示す文字列を変更することはできますが、これらの文字列の内容を変更することはできません。これは、文字列自体がプログラムのデータ セグメントにあり、変更すべきではない場合に重要です。
bar
変更可能な値への定数または固定ポインタです。これは、余分な構文糖のない参照のようなものです。このため、ポインタT* const
を許可する必要がない限り、通常はポインタを使用する場所で参照を使用しますNULL
。