Running C++ code outside of functions scope

Emadpres picture Emadpres · Sep 16, 2014 · Viewed 7k times · Source

(I know) In c++ I can declare variable out of scope and I can't run any code/statement, except for initializing global/static variables.


IDEA

Is it a good idea to use below tricky code in order to (for example) do some std::map manipulation ?

Here I use void *fakeVar and initialize it through Fake::initializer() and do whatever I want in it !

std::map<std::string, int> myMap;

class Fake
{
public:
    static void* initializer()
    {
        myMap["test"]=222;
        // Do whatever with your global Variables

        return NULL;
    }
};

// myMap["Error"] = 111;                  => Error
// Fake::initializer();                   => Error
void *fakeVar = Fake::initializer();    //=> OK

void main()
{
    std::cout<<"Map size: " << myMap.size() << std::endl; // Show myMap has initialized correctly :)
}

Answer

Some programmer dude picture Some programmer dude · Sep 16, 2014

One way of solving it is to have a class with a constructor that does things, then declare a dummy variable of that class. Like

struct Initializer
{
    Initializer()
    {
        // Do pre-main initialization here
    }
};

Initializer initializer;

You can of course have multiple such classes doing miscellaneous initialization. The order in each translation unit is specified to be top-down, but the order between translation units is not specified.