MCU單晶片韌體設計

2022年4月30日 星期六

[C 語言] 有無const 的差異?

 


char *s : 表示s 指標指向一個character
constant char *s : 表示s 指標指向一個constant character; 也就是所指向的字元不能被修改
可以參考底下範例, 觀察有無const 的差別.

#include <stdio.h>
int main()
{
const char str[]="hello";
str[0]='H';
printf(str);
return 0;

}

若是寫 const char *str="hello";
這str 本來就指向read only 的"hello"字串區域, 所以本來就不能更改, 因此
這兩個寫法結果沒有差異, 但用const char * str寫法可以讓別人知道, 不會透過str 來改變指標所指的內容.

char *str="hello"; 
const char *str="hello";