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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章