# C語言中的 `const` 和指標 這篇文章將簡述老師上課所提到的 `const` 和指標,以下會透過例子說明它們如何運作。 ## Case 1 : Const const 在 C 語言中主要用於建立不可變的變數或者確保函數不會更改其參數。 ```c= #include <stdio.h> int main() { // case 1 : constant const int a = 10; // 宣告一個常數整數 a 並初始化為 10 printf("%s %d", "Case 1 Constant Output:", a); // 使用 %d 來輸出整數 a // 輸出為: Case 1 Constant Output: 10 return 0; } ``` ![](https://hackmd.io/_uploads/SkK4I0Wkp.png) ### 若嘗試要修改const的話,則會產生Error ```c= #include <stdio.h> int main() { const int a = 10; printf("%s %d", "Case 1 Constant Output:", a); a = 30; // 嘗試修改 const a printf("%s %d", "Case 1 Constant Output:", a); return 0; } ``` ![](https://hackmd.io/_uploads/S1nbv0Z1T.png) ## Case 2 : const int 的指標 當宣告一個指標時,這表示你不能使用這個指標來改變其所指向變數的值。 可以想像成不能使用*ptr來改變值,但其他方法可以。 ```c= #include <stdio.h> int main() { int a = 10; const int *p = &a; // 宣告一個指標p 指向 a = 10 記憶體的位置 printf("a記憶體位置 %p", &a); printf("\n a value: %d \n", *p); // 輸出: 10 ("*" 是印出記憶體位置的值) int b = 20; p = &b; // 這是可以的,因為你只是改變指標 p 所指向的地址 printf("b記憶體位置 %p", &b); printf("\n b value: %d \n", *p); // 輸出: 20 b = 30; printf("b記憶體位置 %p", &b); printf("\n b value: %d", *p); // 輸出: 30 return 0; } ``` ![](https://hackmd.io/_uploads/BkBYK1zya.png) ### 若嘗試使用*ptr來改變值,則會產生Error ![](https://hackmd.io/_uploads/rk6x1JMJ6.png) ## Case 3 : Const 的指標 這種情況下,指標不能讓它指向其他變數。 ```c= #include <stdio.h> int main() { int a = 10; int *const ptr = &a; printf("a記憶體位置%p", &a); printf("\n a value: %d\n", *ptr); *ptr = 30; printf("a記憶體位置%p", &a); printf("\n a value: %d\n", *ptr); return 0; } ``` ![](https://hackmd.io/_uploads/HkcXc1fk6.png) ### 若嘗試改變指標位置,則會產生Error ![](https://hackmd.io/_uploads/Hk3Cfyzyp.png) ## Case 4 : Const int Const 的指標 既不能改變指標指向的變數的值,也不能讓它指向其他變數。 結合Case 2 + Case 3 特性 ![](https://hackmd.io/_uploads/Hy9eVJMyT.png)