在C中声明两个同名的全局变量 [英] Declaring two global variables of same name in C

查看:197
本文介绍了在C中声明两个同名的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中声明了两个同名的全局变量. 因为我们无法在相同的存储类中声明相同的名称变量,所以应该报错.

I have declared two global variables of same name in C. It should give error as we cannot declare same name variables in same storage class.

我已经在C ++中进行了检查-它给出了编译时错误,但在C中却没有.为什么?

I have checked it in C++ — it gives a compile time error, but not in C. Why?

以下是代码:

int a;
int a = 25;
int main()
{

   return 0;
}

在以下位置进行检查:在Ideone编写的代码

Check it out at : Code Written at Ideone

我认为这可能是原因

C语言中的声明和定义

但是在C ++中不是这种情况.我认为在C ++中,无论变量是在全局范围内声明还是在自动范围内声明和定义都同时发生.

But this is not the case in C++. I think in C++, whether the variable is declared at global scope or auto scope the declaration and definition is happening at the same time.

还有谁能给它更多的启发.

Could anyone throw some more light on it.

现在,当我两次定义变量并赋值两次时,会给我错误 (而不是一个声明和一个定义).

Now when I define the variable two times giving it value two times it gives me error (instead of one declaration and one definition).

位于以下位置的代码:现在有两个定义

Code at : Two definitions now

int a;
int a;
int a;
int a = 25;

int main()
{
return 0;
}

推荐答案

在C中,多个全局变量被合并"为一个.因此,实际上您只有一个全局变量,已多次声明.这可以追溯到C语言中不需要extern(或者可能不存在-不太确定)的时间.

In C, multiple global variables are "merged" into one. So you have indeed just one global variable, declared multiple times. This goes back to a time when extern wasn't needed (or possibly didn't exist - not quite sure) in C.

换句话说,出于历史原因,这在C语言中是有效的,因此我们仍然可以编译在C语言存在ANSI标准之前编写的代码.

In other words, this is valid in C for historical reasons so that we can still compile code written before there was a ANSI standard for C.

尽管如此,为了允许在C ++中使用该代码,我建议避免使用它.

Although, to allow the code to be used in C++, I would suggest avoiding it.

这篇关于在C中声明两个同名的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆