Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

global variables - Why are we not allowed to have assignment statements in the file scope in C?

Why are we only allowed to declare and define variables in global section?Why not include assignment in global section? Example:

#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(){
 ...
}

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?

#include<stdio.h> 
int i=5;
int j=i+5;//[Error] initializer element is not constant
void main(){
 ...
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We are not allowed to use assignment in file scope because program execution starts from main. Compiler creates _start function which is executed first and then jump to main is made from there. When main returns, control goes back to _start which is having proper exit procedure to terminate program. So anything which is written outside the functions is only meant for the initializations which will be done compile time

Initialization is different from declaration and assignment. When we initialize variable compiler will make such arrangement that when program execution starts, its value will be what we have initialized. But when we declare a variable, it will be having default initial value specified by its scope. Assignment is done at runtime and not at compile time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...