Chr*_*fer 1 c compiler-errors const 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;
}
Run Code Online (Sandbox Code Playgroud)
大多数编译器都会愉快地吞下pArray的赋值,但会对nElements的赋值进行扼杀.这种不一致让我感到困惑,我希望能够开悟.
我没有接受你不能分配一个const整数的问题,但是为什么它能像我期望的那样运行const-pointer-to-const?
快速而廉价的修复是删除const限定符,但这可能会引入微妙的错误,因为循环中的大部分代码都是宏命令的(我曾经被它咬过一次).您将如何重构上述内容以允许一个恒定的元素计数器?
正如米歇尔所指出的,你的声明:
const int const * pArray;
Run Code Online (Sandbox Code Playgroud)
不太正确.
你有四(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 */
Run Code Online (Sandbox Code Playgroud)
在你的宣言中 pArray
const int const * pArray;
Run Code Online (Sandbox Code Playgroud)
两个'const'关键字实际上都适用于int.要使一个应用于指针,您必须将其声明为int const * const pArray,其中指针本身变为不可变.然后,您的编译器应该在两个赋值上抛出错误.
| 归档时间: |
|
| 查看次数: |
4093 次 |
| 最近记录: |