mercredi 27 février 2019

How to avoid using global in C to detect setting of variable?

I have function foo() which is called from two different code flows. Lets say these two code flows have two different functions calling foo()

bar() and tar()

I want to do make some decision on the basis of which function(bar() or tar()) has called foo(). Currently, I am setting global variable IN_BAR = 1; in case of bar() and IN_BAR = 0; in case of tar. Then I check the value of "IN_BAR" in foo() and do something.

int IN_BAR = 0; // global

void bar () {
...
IN_BAR = 1;
foo();
IN_BAR = 0;
..
}

void tar() {
...
foo();
...
}

void foo() {
...
if (IN_BAR)
   do_this();
else
   do_that();
}

Currently, there is a lot of places (in codebase) which look like this. I want to avoid using globals and setting & resetting of global variables. Is there way to handle the above mentioned situation? Or is there a design flaw here?

Aucun commentaire:

Enregistrer un commentaire