I’ve been wondering for a while why initializing any data by passing it to some function is not permitted despite the fact that constructors that are a kind of function anyway can be called at global scope, so if we have something like an array at global scope it can’t be initialized by any function but if it was in an object of a structure at global scope then it could be initialized using a constructor at the scope:
//global scope
char charArray[100];//can't be initialized using any function at global scope but in other scopes it could by being passed to some function
struct Test{
public:
Test(){
//initialization
}
char charArray[100];
};
Test obj();//now charArray can be initialized using constructor at global scope
Actually you can call functions at global scope.
It’s just the way that C was designed years ago that you can’t have functions run on their own at global scope. All program code starts at
main.In general, the less you depend on global initialization (avoid it if possible), the less you’ll have to worry about weird static-init errors and such problems randomly cropping up.
Arrays are a different case because you can never assign the result of a function call to an array – the only way to initialize it in this case is inside a constructor as you observed.
EDIT: Somewhat evil approach to initialize an array inspired by a comment:
This only works since within a translation unit the order of creation/initialization of globals is guaranteed to be the order they appear in the file.