C和C++中全局變量及const變量的區別

碰到個問題折騰了半天,是C和C++中全局變量以及全局const變量的鏈接特性和可見性的問題,先摘錄一段C++編程思想裏的文字:

In C++, a const doesn't necessarily create storage. In C a const always creates storage. Wheater or not storage is reserved for a const in C++ depends on how it is used. In general, if a const is used simply to replace a name with a value(just as you would use a #define), then storage doesn't have to be created for the const. If no storage is created(this depends on the complexity of the data type and the sophistication of the compliler), the values may be folded into the code for greater efficiency after type checking, not before, as with #define. If, however, you take an address of a const(even unknowingly, by passing it to a function that takes a reference argument) or you define it as extern, then the storage is created for the const.

C中,比如a.c和b.c中,如果兩個文件同時出現同名的全局變量且並沒有在兩個文件裏都初始化時,是可以編譯通過的,但請不要那麼寫。好,看代碼:

/*     a.c    */
#include <stdio.h>
int a=9;
const int x= 100;
void test();

int main(){
        printf("a=%d   x = %d\n", a, x);
        test();
}

/*     b.c    */
#include <stdio.h>
int a; //如果這裏給a賦值: int a=12; 就會編譯時報錯; 這裏最好寫成extern int a;
const int x; //如果這裏給x賦值: int x=200; 就會編譯時報錯; 這裏最好寫成extern const int x;

void test(){
    ++a;
    printf("in test a = %d const x=%d \n", a, x);
}
    C語言中的const變量是隻讀變量,且佔用內存,C的const全局變量是外部鏈接的,C++正好相反。C++的const全局變量是內部鏈接的,所以如果在多個文件中同時出現同名的const全局變量是沒有問題的。如果要使用,需要像下面那樣:

/*   a.cpp */
#include <iostream>
using namespace std;
int a = 9; //在c++中,如果a.cpp和b.cpp同時出現全局的int a;即使都沒有初始化,也編譯不過,這和C不同
extern const int b = 5; //要讓b.cpp中可以訪問這個b,需要在這裏用extern且對其初始化
void test();

int main(){
        printf("a=%d b=%d\n", a, b);
        test();
        printf("int main 2222 b=%d", b);
}

/*   b.cpp */
#include <stdio.h>
extern int a; //在c++中,如果a.cpp和b.cpp同時出現全局的int a;即使都沒有初始化,也編譯不過,這和C不同
extern const int b; // 這裏用extern說明該const b在別的文件定義。

void test(){
    ++a;
    printf("in test a = %d b=%d\n", a, b);
}

轉自:http://hi.baidu.com/bmrs/blog/item/4643d23708803dd3a3cc2bed.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章