C++ const对象 和 C const对象的区别之一 —— 默认作用域

作用域

C++

在全局作用域中声明的const变量是定义该对象文件的局部变量。

//var.c
extern const int MAX = 100; //必须用extern显式的声明const变量为全局变量
const int MAX_TEST = 100;   //默认construction

//main.cpp
using namespace std;

extern const int MAX;
extern const int MAX_TEST;

void foo()
{
    const int FOO = 255;        //作用域为函数的局部变量
    cout << "FOO=" << FOO << endl;
}

int main()
{
    int x = MAX;         //correct, 声明全局const变量,必须使用extern关键字做显示声明
    cout << "x = " << x << endl;

    int y = MAX_TEST;    //compile error, 在全局作用域中声明的const对象,
                         //默认为文件的局部变量。NAX_TEST的作用域是var.cpp

    extern const int FOO;
    int z = FOO;         //compile error, 非全局作用域声明的const对象,
                         //与非全局作用域声明的const对象的作用域一样

    return 0;
}



$ g++ main.cpp var.cpp 
/tmp/ccWHb099.o: In function `main':
main.cpp:(.text+0x76): undefined reference to `MAX_TEST'
main.cpp:(.text+0x7f): undefined reference to `FOO'
collect2: ld returned 1 exit status


C

在全局作用域中声明的const变量和非const变量的作用域都是一样的。

//var.c
const int  MAX = 1024;

//main.c
#include <stdio.h>

extern int MAX;

int main()
{
    printf("MAX=%d\n", MAX);
    return 0;
}

$ gcc main.c var.c



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值