是否可以定义仅由两个函数可见的局部静态变量?
Is it possible to define local static variable which is visible only by two functions?
我想知道 C 语言是否允许定义一个仅供 2 个函数使用的局部静态变量。所以其他函数将无法 see/use 这个变量。
例如:
int f1(){
static int i = 0;
// some instructions here
i = 10;
// rest of code
}
int f2(){
i = 0; // must be the same i variable in f1 function.
// rest of code
}
有没有办法告诉C编译器f2
的i
变量与f2
i
变量相同?
不,不是真的。您基本上必须通知第二个函数变量的地址,并从那里取消引用它,这样它们都使用相同的内存地址。
或者,将这两个函数分解为它们自己的 文件,其中 static
的工作方式略有不同 (a):
static int i = 0;
int f1(){
// some instructions here
i = 10;
// rest of code
}
int f2(){
i = 0; // must be the same i variale in f1 function.
// rest of code
}
该文件之外的任何人都无法访问 i
,但您可能需要一个更好的名称:-)
(a)通俗地说,在一个函数中,它实际上只是控制变量的生命周期而不是什么可以访问它(只有函数本身可以访问它)。生命周期允许它在函数结束后继续存在,在您下次重新进入该函数时具有相同的值。
在函数之外,static
不影响生命周期,只影响可以访问它的东西(文件之外的任何东西都无法访问它)。
我想知道 C 语言是否允许定义一个仅供 2 个函数使用的局部静态变量。所以其他函数将无法 see/use 这个变量。
例如:
int f1(){
static int i = 0;
// some instructions here
i = 10;
// rest of code
}
int f2(){
i = 0; // must be the same i variable in f1 function.
// rest of code
}
有没有办法告诉C编译器f2
的i
变量与f2
i
变量相同?
不,不是真的。您基本上必须通知第二个函数变量的地址,并从那里取消引用它,这样它们都使用相同的内存地址。
或者,将这两个函数分解为它们自己的 文件,其中 static
的工作方式略有不同 (a):
static int i = 0;
int f1(){
// some instructions here
i = 10;
// rest of code
}
int f2(){
i = 0; // must be the same i variale in f1 function.
// rest of code
}
该文件之外的任何人都无法访问 i
,但您可能需要一个更好的名称:-)
(a)通俗地说,在一个函数中,它实际上只是控制变量的生命周期而不是什么可以访问它(只有函数本身可以访问它)。生命周期允许它在函数结束后继续存在,在您下次重新进入该函数时具有相同的值。
在函数之外,static
不影响生命周期,只影响可以访问它的东西(文件之外的任何东西都无法访问它)。