用C以外的主要变量的作用域 [英] Scope of a variable outside main in C

查看:112
本文介绍了用C以外的主要变量的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑code:

#include <stdio.h>

int x;

int main (void) 
{ }

X 0 的值。但是,这是为什么?我还没有宣布它为静态。或者是它假定静态,因为它是一个功能之外?

The value of x is 0 inside main. But why is that? I have not declared it to be static. Or is it assumed static as it is outside a function?

如果上面是真实的,它是如何使它从的extern不同

If the above is true, how does it make it different from an extern?

推荐答案

这是既不静态也不的extern 。这对编译单元它在一个变量可见的,并且还将会从申报 X 是一个的extern 变量。

It's neither static nor extern. It's a variable visible for the compilation unit it's in, and additionally will be visible from all compilation units that declare x to be an extern variable.

为什么我说这是既不静态也不的extern

Why am I saying it's neither static nor extern?

如果是的extern ,那么,就必须以不同的编译单元X 声明就可以了。显然,这是你唯一的编译单元。

If it was extern, then, there must be a different compilation unit with x declaration on it. Clearly this is your only compilation unit.

如果是静态那么,没有的extern 引用将被允许 X 在这个编译单元定义的变量。我们知道,我们可以很容易地声明的extern 变量此 X 宣布在这里。

If it was static then, no extern reference would be allowed to x variable defined in this compilation unit. We know that we could easily declare an extern variable to this x declared here.

为什么 0 分配到 X ?因为,在 C ,所有全局变量初始化为 0 。它说,所以在C99标准6.7.8(10)。

Why is 0 assigned to x? Because, in C, all global variables initialize to 0. It says so in 6.7.8 (10) of the C99 standard.

这篇关于用C以外的主要变量的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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