In C, suppose var1 is a variable in foo1() and foo2() wants to access var1, however, foo1() doesn\'t call foo2(), so we can\'t pass it by parameter. At the same time, only foo1(
This answer is inspired by the 'Module' concept, found in many other languages, which can be approximated using gcc's nested functions. Variable var1
is within scope for both foo1()
and foo2()
, but is out of scope for everything else. The solution uses neither global vars nor parameters.
void foo(int fn)
{
static int var1;
void fn1(void)
{
var1 = 15;
}
void fn2(void)
{
var1 = 20;
}
(fn == 1)? fn1(): fn2();
printf("Value of var1 is now %d\n", var1);
}
void foo1(void){foo(1);}
void foo2(void){foo(2);}
int main (void)
{
foo1();
// Expected stdout: Value of var1 is now 15
foo2();
// Expected stdout: Value of var1 is now 20
}