c - 为什么我不能分配一个 const 值,我应该怎么做?

标签 c constants compiler-errors c99

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

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

最佳答案

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

关于c - 为什么我不能分配一个 const 值,我应该怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/975436/

相关文章:

c - 系统如何知道访问的地址是常量还是非常量

c++ - 常量引用 - C++

c - gets() 到达 '\r' 或 '\n' 或 '\r\n' 时是否停止读取?

c - 向 int 字符串添加前缀

javascript - 是否可以在javascript的函数中定义一个全局常量

动画示例中的 Java Lang nullpointerException?

java - "A JNI Error has occurred"对于程序的一个实例,而不是另一个

angular - ng2-completer-生产版本中产生错误

c - 结构格式的 atof() 函数测试用例

c - 如何删除带有随机指针的链表?