How to share a variable between two functions in C?

后端 未结 6 1849
抹茶落季
抹茶落季 2021-01-22 16:27

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(

6条回答
  •  深忆病人
    2021-01-22 17:27

    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
    }  
    

提交回复
热议问题