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

全局变量与局部变量的重新定义

发布时间:2020-12-16 06:00:35 所属栏目:百科 来源:网络整理
导读:参见英文答案 Multiple declarations and definitions3 当我编译下面的代码 #includestdio.hint main(){ int a; int a = 10; printf("a is %d n",a); return 0;} 我收到一个错误: test3.c: In function ‘main’:test3.c:6:5: error: redeclaration of ‘a
参见英文答案 > Multiple declarations and definitions3
当我编译下面的代码
#include<stdio.h>

int main()
{
  int a;
  int a = 10;
  printf("a is %d n",a);
  return 0;
}

我收到一个错误:

test3.c: In function ‘main’:
test3.c:6:5: error: redeclaration of ‘a’ with no linkage
test3.c:5:5: note: previous declaration of ‘a’ was here

但是如果我使变量为全局,那么它可以正常工作.

#include<stdio.h>

int a;
int a = 10;
int main()
{
  printf("a is %d n",a);
  return 0;
}

为什么声明相同的全局变量两次不是错误,但是对于局部变量来说这是一个错误?

解决方法

在C中,语句int a;在文件制作时,是一个声明和暂定的定义.只要所有人都相互匹配,您就可以拥有所需的许多临时定义.

如果一个定义(具有初始化器)出现在翻译单元的结尾之前,变量将被初始化为该值.具有多个初始化值是编译器错误.

如果到达翻译单元的末尾,并且没有找到非暂时的定义,变量将为零初始化.

以上不适用于局部变量.这里一个声明也作为一个定义,并有多个导致错误.

(编辑:李大同)

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

    推荐文章
      热点阅读