Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running C++ code outside of functions scope

(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 :)
}
like image 993
Emadpres Avatar asked Sep 16 '14 08:09

Emadpres


1 Answers

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.

like image 117
Some programmer dude Avatar answered Oct 24 '22 17:10

Some programmer dude