2009-06-10 8 views
1

私は以下のラフ署名付きコードの一部を持っている:なぜconst値を割り当てることができないのですか?代わりに何をする必要がありますか?

void evaluate(object * this) 
{ 
    static const int briefList[] = { CONSTANT_A, CONSTANT_Z }; 
    static const int fullList[] = { CONSTANT_A, CONSTANT_B, ..., CONSTANT_Z}; 

    const int const * pArray; 
    const int nElements; 
    int i; 

    if (this->needDeepsEvaluation) 
    { 
     pArray = fullList; 
     nElements = sizeof(fullList)/sizeof(fullList[0]); 
    } 
    else 
    { 
     pArray = briefList; 
     nElements = sizeof(briefList)/sizeof(briefList[0]); 
    } 

    for (i = nElements; i; i--) 
    { 
     /* A thousand lines of optimized code */ 
    } 
    this->needsDeepEvaluation = 0; 
} 

ほとんどのコンパイラは喜んpArrayの割り当てを飲み込むが、nElementsの割り当てにチョークます。この矛盾は私を混乱させ、私は悟りたい。

私はあなたがconstの整数を割り当てることができないことを受け入れて問題ありませんが、私はのconstへのポインタのconstのために期待するとして、なぜそれが機能しませんか?

迅速かつ安価な修正が修飾constをドロップすることですが、ループ内のコードの多くは(私は一度それにかましてきた)macrofiedあるので、それは微妙なバグを紹介するかもしれません。あなたは一定の要素のカウンターを許可するために上記をどのように再構成しますか?

答えて

5

'のconst' キーワードは、実際にintに適用されます。 1つをポインタに適用するには、int const * const pArrayと宣言しなければなりません。ポインタ自体は不変になります。コンパイラは両方の割り当てにエラーを投げます。

+0

私はこれを受け入れるだろう:

あなたは4(4)syntaticの選択肢があります。 – Christoffer

0

私はpArrayとまで何見当がつかないが、nElementsのためにあなただけの場合は、他の代わりの三元を使用することができます。

const int nElements = this->needsDeepEvaluation ? sizeof(fullList)/sizeof(fullList[0]) | sizeof(briefList)/sizeof(briefList[0]); 

あなたが三元系が好きではない場合は、nElementsを計算少し関数を宣言、それを使用して初期化します。 pArray

const int const * pArray; 

両方のあなたの宣言で

9

ミシェルが指摘したように、あなたの宣言:

const int const * pArray; 

は全く正しくありません。それが最も簡潔な答えだから

int * pArray;  /* The pointer and the dereferenced data are modifiable */ 
int * const pArray; /* The pointer is constant (it should be initialized), 
         the dereferenced data is modifiable */ 
int const * pArray; /* the pointer is modifiable, the dereferenced data 
         is constant */ 
int const * const pArray; /* Everything is constant */ 
関連する問題