作者FRAXIS (喔喔)
看板C_and_CPP
標題[心得] const指標的整理
時間Sat Apr 10 09:15:16 2010
以前曾經整理過const, static, vla指標的宣告和定義方法,供大家參考,
看看有沒有遺漏的case。
void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst );
但是還有很多種變形
const int* ptrToConst;
const int* const constPtrToConst
const (int *) ptrToConst;
(int *) const constPtr;
如果配合上int * = int []的話
int ptr[];
const int ptrToConst[];
int constPtr[const]; // C99 new feature
const int constPtrToConst[const];
基本上,不考慮()的話,就是從*切成兩半,
const在*左邊就是形容指向的內容,const在*的右邊就是形容指標。
又,C99有提供了VLA和static,所以整理一下
void f( int n, int array[] ); // 合法,C90慣用法
void f( int n, int array[10] ); // 合法,但是有沒有那10根本就沒差
void f( int n, int array[n] ); // 合法,告訴編譯器array長度是n
void f( int n, int array[*] ); // 合法,告訴編譯器array是vla (只能用在宣告)
void f( int n, int array[static 10] ); // 合法,告訴編譯器array長度至少有10
void f( int n, int array[static n] ); // 合法,告訴編譯器array長度至少有n
以往在ANSI C的年代,要搞定二維陣列都很麻煩,把陣列傳給一個
函式的時候,除了第一維度可以省略之外,其他維度的大小都需要知道。
f( int n, int m, int matrix[][] ); // 非法
f( int n, int m, int matrix[][MAX] ); // 合法,但是MAX是固定的
如果要函式可以任意接受維度不同的陣列,在ANSI C的解法就是要
手動計算index,非常的麻煩。
但是在C99之中,可以這樣宣告
f( int n, int m, int matrix[][*] );
f( int n, int m, int matrix[*][*] );
定義寫成
f( int n, int m, int matrix[][m] );
f( int n, int m, int matrix[n][m] );
如此一來,就可以讓編譯器自己去計算index了,至於要讓這程式跟
動態配置的陣列混用的話,必需要使用一維陣列模擬二維陣列的方法。
另外static只能使用在最高維度上面
f( int n, int m, int matrix[static n][m] ); // 合法
f( int n, int m, int matrix[m][static m] ); // 非法
f( int n, int m, int matrix[static n][static m] ); // 非法
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.119.162.50
推 cutecpu:推!(Y) 04/10 14:39
推 VictorTom:推:) 04/10 14:43
推 akasan:推,有些目前都還沒用過看過...那個...跟C++的相容性勒XD? 04/10 15:00
推 weiyucsie:推~ 04/10 15:57
推 nowar100:vla的東西跟C++不相容吧 @_@ 04/10 16:21
推 Bencrie:請把 C 跟 C++ 視為不同的語言 XD 04/10 16:46
推 hilorrk:Stroustrup表示: 04/10 16:49
→ tinlans:GCC 4.5 新功能,用 -Wc++-compat 檢查 C 程式是否跟 C++ 04/11 02:15
→ tinlans:相容。 04/11 02:15
→ tinlans:不過如果是有做 extension 的,我猜它不會 warning。 04/11 02:16
推 xxxx9659:推推 05/23 05:16