【问题标题】:Why can't I assign a const value, and what should I do instead?为什么我不能分配一个 const 值,我应该怎么做?
【发布时间】:2009-06-10 13:05:40
【问题描述】:

我有一段带有以下粗略签名的代码:

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 限定符,但这可能会引入一些微妙的错误,因为循环内的大部分代码都是宏化的(我曾经被那个咬过)。您将如何重组上述内容以允许使用常量元素计数器?

【问题讨论】:

    标签: c constants compiler-errors c99


    【解决方案1】:

    正如 Michiel 指出的,您的声明:

    const int const * pArray;
    

    不太正确。

    您有四 (4) 个句法选择:

    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 */
    

    【讨论】:

      【解决方案2】:

      在你的pArray声明中

      const int const * pArray;
      

      两个 'const' 关键字实际上都适用于 int。要让一个应用于指针,您必须将其声明为int const * const pArray,其中指针本身变得不可变。然后你的编译器应该在这两个分配上都抛出一个错误。

      【讨论】:

        【解决方案3】:

        我不知道 pArray 是怎么回事,但是对于 nElements,您可以只使用三元而不是 if-else:

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

        如果您不喜欢三元组,请声明一个计算 nElements 的小函数,并使用它来初始化。

        【讨论】:

          猜你喜欢
          • 2021-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-16
          • 2011-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多