當前位置:才華齋>計算機>C語言>

總結C語言中const關鍵字的使用

C語言 閱讀(1.3W)

什麼是const?常型別是指使用型別修飾符const說明的型別,常型別的變數或物件的值是不能被更新的。以下是為大家分享的總結C語言中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是不能進行修改的