gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:14:51 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com