zhiwenf zhiwenf - 3 months ago 8
C Question

How to share a variable between two functions in C?

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() and foo2() will access it, so I wouldn't like to declare it as global variable. It will be similar with the "friend semantics" in c++, is there any way to implement this in C?

void foo1() {
...
var1;
....
}


void foo2() {
...
how to access var1?
...
}

Answer

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.