2009-06-10 2 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-pointer-to-const에 대한 기대로 작동하는 이유는 무엇입니까?

신속하고 값싼 수정은 const 한정자를 삭제하는 것이지만 루프 내부의 많은 코드가 매크로화되어 있기 때문에 미묘한 버그가 발생할 수 있습니다. 당신은 일정한 원소 계수기를 허용하기 위해 위의 구조를 어떻게 재구성 할 것입니까?

답변

5

'const를'키워드는 실제로 int에 적용됩니다. 하나를 포인터에 적용하려면 포인터를 불변으로 만드는 int const * const pArray으로 선언해야합니다. 그러면 컴파일러는 두 할당 모두에 오류를 발생시킵니다.

const int const * pArray; 

가 아주 정확하지 :

+0

나는 이것을 받아 들일 수 있습니다 :

당신은 4 개의 syntatic 선택이있다. – Christoffer

0

나는 최대 pArray에 무슨 생각이 없지만, nElements 당신은 삼항를 사용하는 대신 경우 - 다른 수 있습니다 : 당신이 ternaries 마음에 들지 않으면

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

, nElements을 계산하는 작은 함수를 선언 , 그것을 사용하여 초기화하십시오. pArray

const int const * pArray; 

모두 당신의 선언에

9

는 미키 엘, 당신의 선언을 지적. 그것이 가장 간결한 대답부터

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 */ 
관련 문제