c - Why's initializing a global variable with return value of a function failing at declaration,but works fine at file scope? -


an 80k reputation contributor r.. told me on can't initialize global variables return value of function that's not considered constant,and global variables must initialized constant.and true words,i following error program expected-- initializer element not constant.here program:

#include<stdio.h> int foo(); int gvar=foo();  //error  int main() { printf("%d",gvar); }  int foo() {  return 8; } 

but in context,i don't understand why followed altered version of above program shows no error @ , works fine.in second program,i initializing same global variable return value of same function foo().can tell me rigorous technical reason variation in results?why initializing global variable return value of function @ it's declaration causing error same initialization same return value works fine when done within function?

#include<stdio.h> int foo(); int gvar;  int main() { gvar=foo(); printf("%d",gvar); }  int foo() { return 8; } 

output 8

the reason behind in order determine value produced function 1 needs execute code, , there no code execution done in c when initializing static , global variables.

compiler , linker work prepare byte image of global memory segment: compiler provides values, , linker performs final layout. @ runtime, image of segment loaded in memory is, without further modifications. happens before code gets executed, no function calls can made.

note not mean not possible technical reason, c designers decided against doing it. example, c++ compiler generates code segment calls constructors of global objects, gets executed before control passed main().


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -