How to share a variable between two functions in C?

后端 未结 6 1899
抹茶落季
抹茶落季 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:10

    you pass the variable to both functions.... in general functions shouldn't hold state.

    quickly you find passing variables is not so nice and becomes fragile, so instead, you pass structs.... then functions start working on the state of structs.

    typedef struct 
    {
        int var1;
    } blah_t;
    
    void foo1(blah_t* b)
    {
        b->var1=0;
    }
    
    void foo2(blah_t* b)
    {
        b->var1++;
    }
    

    this is the very simplistic seed idea behind doing OO C.

提交回复
热议问题