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?
...
}
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.
this is the very simplistic seed idea behind doing OO C.
You need to declare
var1
outside the scope of the functions and then send it as a parameter to both. Alternatively, declare it as a global variable.Regarding similar with the "friend semantics" in c++. C does not have the same capability.
Regarding so we can't pass it by parameter
The only option in
C
for accessing a variable from function to function without passing as a function parameter is to use some type of global scope variable.In the event
void foo1()
andvoid foo2()
exist in different C modules...but you still want to be able to access the same variable, and ensure its value is the same at all times, in all places within your project, then consider using
extern scope
:Within a header file that is common to both (multiple) modules, a project scope global can be implemented as follows.
file.h
file1.c
file2.c
No. The variable only exists on the function stack while
foo1()
is running. The stack will vanish when leaving the function. You could make the variable static to keep it alive, but then you can't access it from the outside either without hacks.by reference is one way: (in this example the memory for
i
is local tocaller()
)global: (usually considered horrible
i
would have a name more likeGLOBAL_I
or something)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 bothfoo1()
andfoo2()
, but is out of scope for everything else. The solution uses neither global vars nor parameters.