# 【C】C 語言型態宣告與解讀 ## Introduction C 語言為**強型別**的語言,對於資料型態規範非常嚴格,因此對於 C 語言中變數的宣告,要能夠解讀與分析,這樣才能夠理解每一個變數或函數或陣列所使用的資料型態是甚麼。 ## Right-left Rule **Right-left Rule** 指得是解讀C語言宣告式的一個規則,也就是先往右邊進行解讀,遇到特定字元再往左邊進行解讀, ### 運算子解讀方式 以下有 3 個基本的運算子 * `*` 中文讀為 "指標指向的是...",而英文則為 `as pointer to ...`,只會在 (辨識字) **左邊**出現 * `[]` 中文讀為 "陣列元素為...",而英文則為 `array of ...` 只會在 (辨識字) **右邊**出現 * `()` 中文讀為 "函數回傳值是...",而英文則為 `function (parameter) returning ...` 只會在 (辨識字) **右邊**出現 ## Step 步驟 1. 找到辨識字(變數名稱或者函數名稱),解讀為 `x` 是 或者 `x` is/as 2. 往辨識字的右邊看,如果看到 * `[]` 解讀為 `x`是陣列,其元素為...,`x` is the array of ... * `()` 解讀為 `x`是函數,其回傳值為...,`x` is the function returning ... 直到遇到 單獨的 `,)` * 如果遇到`(`則表示是`()`的開頭,再次往右開始解讀 * 如果遇到`)`則馬上往左走進行解讀! 3. 接著往辨識字的左邊看,如果遇到 `type` 就直接解讀出來,否則就照上面的列表翻譯出來就好,再向左持續解讀,直到沒有運算子或者遇到單獨的左括號`(` ## 以下為不合法的 C 語言宣告 * `[]()` : 沒有陣列中的元素是函數 * `()()` : 沒有函數中回傳函數 * `()[]` : 沒有函數回傳陣列 但我們可以將其變成指標來使其合法例如 * `xf[]() -> (*x[])()` C 語言無法以函數當成陣列中的元素,只能用指標來指向,因此要變成陣列中的元素為指標,指向的是一個函數 * `ff()() -> (*f())()` C 語言無法回傳函數,一樣要修改成指標,因此要變成 `ff` 為函數,其回傳一個指標,指標指向的是一個函數 * `fa()[] -> (*fa())[]` C 語言無法回傳整個陣列,一樣修改成指標,因此要變成 `fa` 為一個函數,回傳為一個指標,指向的是一個陣列 ## Example * `int *ptr[]` - **英文1** : declare `ptr` as array of pointer to `int` - **英文2** : `ptr` is array of pointer to `int` - **中文** : `ptr`是一個陣列,元素內容為指標,指標指向的是`int` - **中文** : `ptr`是一個指標陣列,指標指向的是`int` * `int (*ptr)[]` - **英文** : declare `ptr` as pointer to array of int - **中文** : 宣告一個陣列指標,陣列元素為`int` > 中文真的很玄 * `int (*compare)(void*, void*)` - 英文:declare `compare` as pointer to function (pointer to `void`, pointer to `void`) returning `int` - 中文:宣告一個 `compare`指標函數,其參數為 `(*void, *void)` ,其回傳值為 `int` * `void **(*d) (int &, char **(*)(char *, char **))` - 英文:declare `d` as pointer to function(ref to `int`, pointer to function (pointer to `char`, pointer to pointer to `char`) returning pointer to pointer to `char`) returning pointer to pointer to `void`. - 中文: 宣告一個指標,其指向的是一個函數,函數參數第一為參照`int`,第二為一個指標,指標其指向一個函數,函數參數為第一指向`char`的指標,第二為指向指標的指標,其指向的指標指向`char`,函數回傳為指標的指標,其指向的指標指向的是`void` * `int ptr[]()` - 不合法的宣告,宣告一個ptr為陣列其元素為函數,要修改為其元素為指標函數。 - `int (*ptr[])()` declare ptr as the array of pointer to function returning int ## Reference 1. [C 語言:輕鬆讀懂複雜的宣告式 (Define and Read the complex declarations)](https://magicjackting.pixnet.net/blog/post/60889356#note4) 2. [你所不知道的C語言:指標篇](https://hackmd.io/@sysprog/c-pointer) 3. [cdecl](https://cdecl.org/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up