为什么我们不允许在C中的文件范围中有赋值语句? [英] Why are we not allowed to have assignment statements in the file scope in C?
问题描述
为什么我们只允许在全局部分中声明和定义变量?为什么不在全局部分中包含赋值?
示例:
#include
int a;
a = 5; //有效,因为它类似于int a = 5;因此初始化为暂定义
a = 8; //无效,因为我们只能有一个初始化程序用于暂时的定义
void main(){
...
}
为什么我们需要这个?如果我们被允许有一个以上的初始化器到一个试验性的定义中,结果会是什么? 我的下一个问题是为什么只允许使用常量初始化器元素? 同样如果这条规则不存在,我们会面临什么后果? 请注意我的问题不完全是为什么会发生这种情况?我试图找出为什么这些限制是在第一位给出的。 对于这两个问题答案都是一样的,在文件范围内没有执行语句或表达式的求值,所有这些都是在编译时完成的。其他语言(C ++是一个例子)有一个动态初始化的模型在程序启动时。这是一个复杂的问题,例如,因为来自不同编译单元的初始化器在它们之间没有自然顺序,但可能隐含地依赖于其他编译器。 SO是一个极好的信息来源,用于这个问题< a>也是如此。 Why are we only allowed to declare and define variables in global section?Why not include assignment in global section?
Example: Why do we need this? What would be the consequences if we were allowed to have more than one initializer to a tentative definition My next question is why only constant initializer elements are allowed? Similarly what would be the consequences we face if this rule was not present? Please note my question is not exactly why this happens? I'm trying to figure why these restrictions were given in the first place. For both questions the answer is the same, in file scope there is no execution of statements or evaluation of expressions, all is done at compile time. Other languages (C++ is an example) have a model for dynamic initialization at program startup. This is a complicated issue, e.g because initializers that come from different compilation units don't have a natural ordering among them, but might implicitly depend on each other. SO is an excelent source of information for this question, too. C tries to stay simple, simple to use for a programmer and simple to implement for compiler builders. 这篇关于为什么我们不允许在C中的文件范围中有赋值语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
#include< stdio.h>
int i = 5;
int j = i + 5; // [错误]初始化元素不是常量
void main(){
...
}
C尽量保持简单,易于编程人员使用,并且易于编译器构建者实现。 #include<stdio.h>
int a;
a=5;//Valid because its similar to int a=5; Therefore a initialiser to a Tentative definition
a=8;//Invalid because We can have only one initialiser for a tentative definition
void main(){
...
}
#include<stdio.h>
int i=5;
int j=i+5;//[Error] initializer element is not constant
void main(){
...
}