<address id="ousso"></address>
<form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
  1. C語言

    C語言中const關鍵字的使用方法

    時間:2025-05-25 12:12:00 C語言 我要投稿
    • 相關推薦

    C語言中const關鍵字的使用方法

      const關鍵字使用非常的靈活,下面我們一起來看看關于C語言中const關鍵字的使用方法,歡迎大家閱讀!

      C語言中const關鍵字的使用方法

      什么是const?

      常類型是指使用類型修飾符const說明的類型,常類型的變量或對象的值是不能被更新的。(當然,我們可以偷梁換柱進行更新:)

      為什么引入const?

      const 推出的初始目的,正是為了取代預編譯指令,消除它的缺點,同時繼承它的優點。

      const關鍵字使用非常的靈活,這一點和php差別很大,php中const用來在類中定義一個常量,而在c中,const因位置不同有不同的作用,因情景不同有不同的角色,使用起來也是非常的靈活。

      (1):const用來修飾普通的變量(指針變量除外)的時候,const type name 和 type const name 這兩種形式是完全等價的,都表示其是常量,不能進行修改。

      #include

      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

      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

      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

      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是不能進行修改的


    【C語言中const關鍵字的使用方法】相關文章:

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

    C語言中Static和Const關鍵字的作用09-23

    C語言關鍵字const用法09-06

    C語言關鍵字const的使用09-02

    c++中const關鍵字11-03

    C語言的const使用方法07-02

    C語言關鍵字:auto、static、register、const08-06

    C語言中volatile關鍵字分析07-26

    C語言中關鍵字volatile的含義07-22

    <address id="ousso"></address>
    <form id="ousso"><track id="ousso"><big id="ousso"></big></track></form>
    1. 日日做夜狠狠爱欧美黑人