Jane
Jane

Reputation: 65

Determine if function was called without setting global variable

What is a good technique to determine if a function was called in C++ without setting a global variable?

#include <iostream>

bool var = false;

void X ()
{
    if (var) {std::cout<<" Y called "<< std::endl;}
}

void Y ()
{var = true;}

int main()
{
Y();
X();
}

I would really like an example of a way to do this without setting a global variable.

Upvotes: 0

Views: 102

Answers (2)

Pete Becker
Pete Becker

Reputation: 76438

The usual way is with a static local variable:

void X() {
    static bool done = false;
    // whatever
    done = true;
}

The static variable is initialized the first time that the function runs. On subsequent calls it has whatever value was last assigned to it.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234785

If Y and X are related in this way, then you could move them to a class:

struct Foo
{
    void X()
    {
         if (var) {std::cout<<" Y called "<< std::endl;}
    }
    void Y()
    {
        var = true;
    }
    Foo() : var(false) /*this is the constructor*/
    {
    }
private:
    bool var;      
};

You could even make the members static, if you didn't want to have to bother with an instance of Foo.

Note also the use of a constructor. Perhaps you could put your initialisation stuff in there; then you wouldn't need to check the initialisation state in X.

Upvotes: 2

Related Questions