觀察到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