代码之家  ›  专栏  ›  技术社区  ›  Christoffer

为什么我不能指定一个常量值,我应该怎么做?

  •  1
  • Christoffer  · 技术社区  · 16 年前

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

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

    3 回复  |  直到 16 年前
        1
  •  5
  •   Michiel Buddingh    16 年前

    在你的声明中 pArray

    const int const * pArray;
    

    两个“const”关键字实际上都适用于 int . 要使一个应用于指针,您必须将其声明为 int const * const pArray ,其中指针本身变得不可变。然后,编译器应该在两个赋值上都抛出一个错误。

        2
  •  9
  •   Jamie    16 年前

    正如米切尔指出的,你的声明:

    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 */
    
        3
  •  0
  •   Jacob B    16 年前

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

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

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

    推荐文章