1. 程式人生 > >C++筆記 第三課 進化後的const分析---狄泰學院

C++筆記 第三課 進化後的const分析---狄泰學院

如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。 學習C++編譯環境:Linux

第三課 進化後的const分析

1.C語言中的const

const修飾的變數是隻讀的,本質還是變數 const修飾的區域性變數在棧上分配空間 const修飾的全域性變數在只讀儲存區分配空間 const只在編譯期有用,在執行期無用 const修飾的變數不是真的常量,它只是告訴編譯期該變數不能出現在賦值符號的左邊。 C語言中的const使得變數具有隻有隻讀屬性 const將具有全域性生命週期的變數儲存於只讀儲存區 const不能定義真正意義上的常量!enum可以,列舉

3-1.cpp C/C++中的const

#include <stdio.h>
int main()
{
    const int c = 0;
    int* p = (int*)&c;
    
    printf("Begin...\n");
    *p = 5;
    
    printf("c = %d\n", c);
    printf("*p = %d\n", *p);
    
    printf("End...\n");
    
    return 0;
}
test.c中結果
[email protected]:~/c++$ gcc test.c
[email protected]
:~/c++$ ./a.out Begin... c = 5 *p = 5 End... 3-1.cpp中結果 [email protected]:~/c++$ g++ 3-1.cpp [email protected]-virtual-machine:~/c++$ ./a.out Begin... c = 0 *p = 5 End...

2.C++中的const

C++在C的基礎上對const進行了進化處理 當碰到const宣告時在符號表中放入常量 編譯過程中若發現使用常量則直接以符號表中的值替換 編譯過程中若發現下述情況則給對應的常量分配儲存空間 對const常量使用了extern 對const常量使用&操作符 注:C++編譯器雖然可能為const常量分配空間,但不會使用其儲存空間中的值。

C語言中的const變數 C語言中的const變數是隻讀變數,會分配儲存空間 C++中的const常量(由只讀變數成真正的常量) 可能分配儲存空間 當const常量為全域性,並且需要在其它檔案中使用 當使用&操作符對const常量取地址 C++中的const常量類似於巨集定義 const int c = 5; ≈#define c 5 C++中的const常量在與巨集定義不同 const常量是由編譯器處理 編譯器對const常量進行型別檢查和作用域檢查 巨集定義由前處理器處理,單純的文字替換

3-2.cpp const與巨集

#include <stdio.h>
void f()
{
    #define a 3
    const int b = 4;
}
void g()
{
    printf("a = %d\n", a); //cpp看到的為printf("a = %d\n", 3);
    //printf("b = %d\n", b); //cpp報錯,沒有在當前作用域起作用
}
int main()
{
    const int A = 1;
    const int B = 2;
    int array[A + B] = {0};
    int i = 0;
    
    for(i=0; i<(A + B); i++)
    {
        printf("array[%d] = %d\n", i, array[i]);
    }
    
    f();
    g();
    
    return 0;
}
test.c中結果
[email protected]:~/c++$ gcc test.c
test.c: In function ‘main’:
test.c:19:5: error: variable-sized object may not be initialized
     int array[A + B] = {0};
     ^
test.c:19:25: warning: excess elements in array initializer
     int array[A + B] = {0};
                         ^
test.c:19:25: note: (near initialization for ‘array’)
3-1.cpp中結果
[email protected]:~/c++$ g++ 3-2.cpp
[email protected]:~/c++$ ./a.out
array[0] = 0
array[1] = 0
array[2] = 0
a = 3
End...

小結

與C語言不同,C++中的const不是隻讀變數 C++中的const是一個真正意義上的常量 C++編譯器可能會為const常量分配空間 C++完全相容C語言中const常量的語法特性