Why initializing data at global scope by passing it to some function is not possible?

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{
      char charArray[100];
    Test obj();//now charArray can be initialized using constructor at global scope


Actually you can call functions at global scope.

int foo()
    return 5;

int bar = foo();

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:

bool do_init(int a[50])
    // Do whatever to init the array here.
    return true;

int array[50];
bool init_array = do_init(array);

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.

Need Your Help

Active-X vs Ajax Internet client-server communication

ajax activex client-server polling

I have to use scanner on Internet site web page. As far as I know not Flash nor Silverlight is capable to communicate with such hardware nowadays. It looks like there is no alternative to Active-X at

Refreshing a Partial with Ajax in Rails 3 with Jquery

ruby-on-rails ruby ajax jquery

I have a partial that has a container that holds a bunch of items. If I add an item via ajax, I want to reflect that in this container without refreshing the page. I am having an issue finding a

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.