观察到const
可以应用于一个指针参数有以下几种:由于数组衰减为指针,为什么我不能应用const?
void fn1(int * i){
*i = 0; //accepted
i = 0; //accepted
}
void fn2(int const* i){
*i = 0; //compiler error
i = 0; //accepted
}
void fn3(int *const i){
*i = 0; //accepted
i = 0; //compiler error
}
void fn4(int const*const i){
*i = 0; //compiler error
i = 0; //compiler error
}
我现在有一个数组语法尝试同样的事情。如你所知,当作为参数传递时,数组会衰减为指针。
因此,行为应该是相同的。
但是,我不能将const应用于腐朽的指针,同时使用数组语法。
void fn1(int i[]){
*i = 0; //accepted
i = 0; //accepted
}
void fn2(int const i[]){
*i = 0; //compiler error
i = 0; //accepted
}
void fn3_attempt1(int i[] const){ //<-- can't apply const this way
*i = 0; //accepted
i = 0; //compiler error
}
void fn3_attempt2(int i const[]){ //<-- can't apply const this way
*i = 0; //accepted
i = 0; //compiler error
}
...
是否有任何的方式来传递使用数组语法的阵列,但要避免重新分配指针?
限定符必须*先于*变量才能被限定。 (感谢Olaf) –
@ DavidC.Rankin:'const'是一个精确的_qualifier_。 – Olaf
'int const'是不建议使用的语法和过时的功能。限定符应该在类型前面。目前尚不清楚你的意思。 'int i []'作为形式参数转换为'int *' – Olaf