在C中使用文件范围声明和分配变量 [英] Declaring and assigning variables with file scope in C

查看:102
本文介绍了在C中使用文件范围声明和分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我声明以下变量:

int num;
num = 0;

int main(void)
{
        /* ... */
        exit(EXIT_SUCCESS);
}

编译器将抱怨未声明num,并且默认将其键入int.当我一步完成所有操作时,不会发生这种情况:

The compiler will complain about num being undeclared and that it will default to type int. This does not happen when I do it all in one step:

int num = 0;

或者如果我将作业移至main():

or if I move the assignment into main():

int main(void)
{
        num = 0;
        /* ... */
        exit(EXIT_SUCCESS);
}    

我曾经阅读过这种行为的解释,但现在找不到了.有人可以再次更新我吗.

I once read an explanation for this behavior but I cannot find it anymore. Could someone update me again.

我正在使用

gcc -std=c11 -O2 -g -pedantic -Wall -c -fmessage-length=0 -v

推荐答案

num = 0;是只能在函数内部存在的语句.它不能存在于全球范围内.

num = 0; is a statement that can exist only inside a function. It cannot exist in a global scope.

如果将语句放在函数外部,这是错误的,也是不允许的.简单地想一下,如果您在全局范围内在所有函数之外都拥有一条语句,那么该语句何时以及如何执行?所以,那是错误的.

If you put a statement outside a function, it's wrong and not allowed. Simply think this like, if you have a statement outside all the functions, in a global scope, when and how that statement can be executed? So, that's wrong.

在一种特殊情况下,允许以int num = 0;

A special case, initialization while defining is allowed in a form of int num = 0;

这篇关于在C中使用文件范围声明和分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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