C言語の const とポインタの * の並び順の意味について、忘れちゃったので、改めて調べてみましたので、それのメモです。
実際にコンパイルしてみるのが早いので、次のコードを書いて gcc でコンパイルしてみました。
コメントは、その行に出た警告かエラーです。
int main(void)
{
const int a = 0;
const int b = 1;
int *p0 = &a; /* warning: initialization discards qualifiers from pointer target type */
const int *p1 = &a;
int const *p2 = &a;
int * const p3 = &a; /* warning: initialization discards qualifiers from pointer target type */
const int * const p4 = &a;
int const * const p5 = &a;
p0 = &b; /* warning: assignment discards qualifiers from pointer target type */
p1 = &b;
p2 = &b;
p3 = &b; /* error: assignment of read-only variable 'p3' */
p4 = &b; /* error: assignment of read-only variable 'p4' */
p5 = &b; /* error: assignment of read-only variable 'p5' */
return 0;
}
これによって、次のようなルールがありそうです。
- 型の前の const は、実体領域に書き込めない事を表す
- 型の後ろの const は、実体領域に書き込めない事を表す
- ポインタ演算子 (*) の後ろの const は、ポインタ変数に書き込めない事を表す
全てのパターンを網羅した表は次のようになるでしょう。
| パターン | 実体領域への書込(*p = 2) | ポインタ変数への書込(p = &b) |
|---|---|---|
| int *p = &a; | ○ | ○ |
| const int *p = &a; | × | ○ |
| int const *p = &a; | × | ○ |
| int * const p = &a; | ○ | × |
| const int * const p = &a; | × | × |
| int const * const p = &a; | × | × |