cockatiel
cockatiel

Reputation: 95

C++ Why is it not possible to invoke functions globally without initializing new variables?

If I had to run functions in the global scope e.g. in order to populate a static container in several cpp-files, then each time such a function is invoked I would have to initialize a new variable as well, even though I do not need them.
Here is a simplified example for such dummy variables.

static bool foo() { /*some code*/ return true; }
static bool foo2() { /*some code*/ return true; }
static bool bDummy1 = foo();
static bool bDummy2 = foo2();

Technically bDummy1 and bDummy2 are superfluous, but because of the C++ syntax it is still required. Why is there no other way to solve this?
I know it creates very little overhead to create such superfluous variables and the static keyword makes them only locally visible in cpp-files, but that is still not a good coding style.

Upvotes: 1

Views: 151

Answers (2)

Jarod42
Jarod42

Reputation: 218138

each time such a function is invoked I would have to initialize a new variable as well

You don't need several variables by TU, only one is sufficient:

static bool bDummy1 = foo();
static bool bDummy2 = foo2();

can be replaced by

static bool bDummy = foo(), foo2();

Why is it not possible to invoke functions globally without initializing new variables?

gcc/clang have __attribute__ ((constructor)) to solve that issue

Demo Multi-files Demo

Upvotes: 2

VietnameseBushes
VietnameseBushes

Reputation: 11

I think its mandatory in C++. It can cause some confusion and harder to maintain the code. You can try other methods like

class Initializer {

public:

    static void init() {
        // Initialization code
    }
};

static bool dummy = (Initializer::init(), true);

Upvotes: 1

Related Questions