C和C++中全局变量及const变量的区别

本文探讨了C和C++中全局变量和全局const变量的链接特性和可见性差异。在C++中,const不一定分配存储空间,而C则始终分配。C++的const全局变量具有内部链接,而在C中则是外部链接。当在多个文件中定义同名的const全局变量时,C++允许而C不允许可导致编译错误。同时,C++中未初始化的全局变量在同一文件中重复声明会导致编译错误,而C语言则不会。
摘要由CSDN通过智能技术生成
碰到个问题折腾了半天,是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中,如果两个文件同时出现同名的全局变量且并没有在两个文件里都初始化时,是可以编译通过的,但请不要那么写。好&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值