2016-02-28 62 views
3

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

是否有任何的方式來傳遞使用數組語法的陣列,但要避免重新分配指針?

+0

限定符必須*先於*變量才能被限定。 (感謝Olaf) –

+0

@ DavidC.Rankin:'const'是一個精確的_qualifier_。 – Olaf

+1

'int const'是不建議使用的語法和過時的功能。限定符應該在類型前面。目前尚不清楚你的意思。 'int i []'作爲形式參數轉換爲'int *' – Olaf

回答

6

無法使用數組語法指定指針的常量,因爲它對實際數組沒有意義。

無論如何,函數參數的數組語法都有些混亂。它你真的想要使函數參數const,使用指針語法。

如果您使用C99引入的擴展數組語法中的最小尺寸或多個動態尺寸,恐怕沒有辦法指定指針的常量。這不是一個真正的問題恕我直言。

+0

澄清:你可以使數組成爲'const'。它只是轉換的指針本身,你不能用於語法。不知道現代編譯器是否想要修改指針。 – Olaf

相關問題