C言語とC++言語の宣言でconstが使用される方法の直感的なパターンを見つけるのが難しいです。ここではいくつかの例です:ライン1と2では宣言で "const"がどこにあるのかを理解する
const int a; //Const integer
int const a; //Const integer
const int * a; //Pointer to constant integer
int * const a; //Const pointer to an integer
int const * a const; //Const pointer to a const integer
が、const
は、それが修飾するものである、int
の前または後に来ることができるようです。
- は、どのように、4行目では、コンパイラは
const
がint
ではなく*
(ポインタ)を変更していることを決めるのですか? const
に当てはまるものを判断するためにコンパイラが従うルールは何ですか?*
と同じルールに従っていますか?int const x; // x is a constant int int *const x; // x is a constant pointer to an int int const *x; // x is a pointer to a constant int int const *const x; // x is a constant pointer to a constant int
あなたが
const
を置く場合、これはまだ動作します:あなたは常に右タイプのにconst
を置き、あなたが右から左に文として変数宣言を読むことができると仮定すると、
[clockwise spiral rule](http://c-faq.com/decl/spiral.anderson.html)への義務的なリンク –
配列や関数が含まれていない場合は、単に右から左へ読む* *も役に立ちます: 'int const * const a':' 'a'はconst intへのconstポインタです。 –
Mark、あなたが答えとしてそれを提出したなら、私はそれをチェックしたでしょう。非常に便利で本当に私がそれを理解するのに役立ちます! –