什麼是const?常類型是指使用類型修飾符const說明的類型,常類型的變量或對象的值是不能被更新的。以下是爲大家分享的總結C語言中const關鍵字的使用,供大家參考借鑑,歡迎瀏覽!
爲什麼引入const?
const 推出的初始目的,正是爲了取代預編譯指令,消除它的缺點,同時繼承它的優點。
const關鍵字使用非常的靈活,這一點和php差別很大,php中const用來在類中定義一個常量,而在c中,const因位置不同有不同的作用,因情景不同有不同的角色,使用起來也是非常的靈活。
(1):const用來修飾普通的變量(指針變量除外)的時候,const type name 和 type const name 這兩種形式是完全等價的,都表示其是常量,不能進行修改。
#include <stdio.h>
int main(){
const int num =23;
printf("result=%dn",num);
num =31;
printf("result=%dn",num); //報錯,num是常量,不能修改
}
(2):const用來修飾指針變量的時候,分爲以下四種情況
1、const type *name :這種情況下,const修飾的指針變量name所指向的type類型對象,也就是說指向的這個對象是不能進行修改的,因爲其是常量,而指針變量確實可以進行修改的
#include <stdio.h>
int main(){
int tmp = 23;
const int *num = &tmp;
printf("result=%dn",*num);
(*num) = 24; //報錯,因爲指針num指向的int類型的對象是不能進行修改的
printf("result=%dn",*num);
}
2、type const *name :這種情況下,const修飾的指針變量name所指向的type類型對象,意思完全同上,只是顛倒了以下順序。
#include <stdio.h>
int main(){
int tmp = 23;
int const* num = &tmp;
printf("result=%dn",*num);
(*num) = 24; //報錯,因爲指針num指向的int類型的對象是不能進行修改的
printf("result=%dn",*num);
}
3、type * const name :這種情況下,const修飾的`指針變量name,也就是說這個指針變量的值是不能進行修改的,但是指針變量所指向的對象確實可以修改的
#include <stdio.h>
int main(){
int tmp = 100;
int *const num = &tmp;
printf("result=%dn",*num);
int change = 23;
num = &change; //報錯,因爲指針num是不能進行修改的
printf("result=%dn",*num);
}
4、const type * const name :這種情況下,const修飾的指針變量name以及指針變量name所指向的對象,也就是說這個指針變量以及這個指針變量所指向的對象都是不能進行修改的
(3):const在函數中的參數的作用:
void get_value( const int num ){
num=23; //報錯
}
調用get_value()函數的時候,傳遞num參數到函數,因爲定義了const,所以在函數中num是不能進行修改的