加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C中的给定相同范围内声明相同的变量名称

发布时间:2020-12-16 10:37:43 所属栏目:百科 来源:网络整理
导读:我正在尝试理解C中的存储类说明符.我有两个案子. 这里,在给定的相同范围内,声明相同的变量名称. 情况1: #include iostreamstatic int i; extern int i; int main() { std::coutistd::endl; return 0;} 输出: 0 案例2: #include iostreamextern int i; sta
我正在尝试理解C中的存储类说明符.我有两个案子.

这里,在给定的相同范围内,声明相同的变量名称.

情况1:

#include <iostream>

static int i; 
extern int i; 

int main() {
    std::cout<<i<<std::endl;
    return 0;
}

输出:

0

案例2:

#include <iostream>

extern int i; 
static int i; 

int main() {
    std::cout<<i<<std::endl;
    return 0;
}

得到错误:

prog.cpp:4:12: error: 'i' was declared 'extern' and later 'static' [-fpermissive]
 static int i; 
            ^
prog.cpp:3:12: note: previous declaration of 'i'
 extern int i;

为什么第一种情况正常,而第二种情况却出错?

解决方法

extern有点特殊,因为标有它的声明会查找同一实体的先前声明,如果找到,则使用之前的链接.只有当它找不到时才会声明具有外部链接的新实体.

另一方面,static无条件地声明其实体具有内部链接.

这意味着此代码只是通过内部链接声明和定义i.第二个声明找到第一个并重新使用它的链接.

static int i;
extern int i;

而此代码声明变量具有外部链接,然后声明并定义它以具有内部链接,这是一个错误.

extern int i;
static int i;

这种行为的原因很难跟踪,但最有可能回到C标准前的日子.

在C中,此行为由[basic.link]指定,在最新的N4687草案中为6.5 / 6:

The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type,ignoring entities declared outside the innermost enclosing namespace scope,the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity,the program is ill-formed. Otherwise,if no matching entity is found,the block scope entity receives external linkage.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读