在C语言中,假设var1是foo1()函数中的一个变量,而foo2()想要访问var1,但是foo1()没有调用foo2(),因此我们无法通过参数传递它。同时,只有foo1()和foo2()会访问它,因此我不想将其声明为全局变量。这类似于C++中的“友元语义”,那么在C语言中有没有实现这种功能的方法呢?
void foo1() {
...
var1;
....
}
void foo2() {
...
how to access var1?
...
}
typedef struct
{
int var1;
} blah_t;
void foo1(blah_t* b)
{
b->var1=0;
}
void foo2(blah_t* b)
{
b->var1++;
}
您需要在函数作用域之外声明 var1
,然后将其作为参数发送给两个函数。或者,将其声明为全局变量。
caller()
)void caller()
{
int i = 5;
foo(&i);
bar(&i);
printf("\n final i is %d",i);
}
void foo(int *i)
{
printf("%d",*i);
*i += 5;
}
void bar (int *i)
{
printf("%d",*i);
*i += 5;
}
全局变量:(通常被认为是可怕的 i
应该有一个更像 GLOBAL_I
的名称或类似的东西)
int i = 0;
void caller()
{
i=5;
foo();
bar();
printf("\n final i is %d",i);
}
void foo()
{
printf("%d",i);
i += 5;
}
void bar (int i)
{
printf("%d",i);
i += 5;
}
void foo1()
和void foo2()
,但仍希望能够访问相同的变量,并确保其值在项目的所有位置始终相同,则考虑使用extern scope
:file.h
void foo1(void);
void foo2(void);
extern int var1;
file1.c
#include "file.h"
int var1 = 5; //in only 1 module, declare and initialize the
//extern defined in the common header -file.h-
int main(void)
{
printf("value of var1 is %d\n", var1);//original value of var1
foo1();
printf("value of var1 is %d\n", var1);//var1 modified by foo1()
foo2();
printf("value of var1 is %d\n", var1);//var1 modified by foo2()
return 0;
}
void foo1(void)
{
var1 = 15;//Now that the project global variable
//has already been declared and defined, it can simply
//be used, in this file...
}
file2.c
#include "file.h"
void foo2(void)
{
var1 = 20;... and in this one
}
foo1()
正在运行时才存在。当离开函数时,栈就会消失。你可以将变量设置为静态以保持其存活,但这样你也无法在没有 hack 的情况下从外部访问它。这个答案受到了许多其他语言中的“模块”概念的启发,可以使用gcc的嵌套函数来近似。变量var1
在foo1()
和foo2()
中都在作用域内,但对于其他所有内容都不在作用域内。该解决方案既不使用全局变量也不使用参数。
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
}
foo((fn == 1)? fn1(): fn2());
没有问题吗? - Michi
foo1()
,foo2()
不相互调用。 2) 没有任何函数参数。我实际上很喜欢你的struct *
方法。我经常这样做来避免在项目前端修改参数列表以避免参数列表不断增长。(无论我们添加多少成员,struct *a
都始终是struct *a
)。但考虑到OP的指导方针,我提出了这个想法。谢谢。 - ryyker