[英]How to declare a global variable which is present in only one function?
我需要声明一个全局变量,该变量仅在调用某个 function 时可用。 如果没有调用该 function ,则该变量不应该可用。
void function()
{
// if this function is called then declare int a=10;
// as global so other function can use this
}
我怎么能在 c 中做这样的事情?
C 不能那样工作 - 全局变量在加载时分配,并在程序的整个持续时间内存在,与运行时行为无关。 如果您真的必须知道变量是否已“设置”,您可以包含一个单独的标志:
int global_a;
int global_a_has_been_set = 0;
void f()
{
global_a = 10;
global_a_has_been_set = 1;
}
void elsewhere()
{
if (global_a_has_been_set != 0) { /* ... */ }
}
如果您知道您的变量只能是非负数,那么您也可以使用像-1
这样的特殊标记值来指示该变量尚未“设置”。
但最有可能的是,您应该重新设计您的设计,以便您已经通过其他方式知道您是否需要该变量。
您可以在 function 中定义static
变量,然后它仅在 function 中可用(并在多次调用之间保持其值):
int increment() {
static int x = 0; // Initialize with 0
x++;
return x;
}
void main() {
printf("%d\n", increment());
printf("%d\n", increment());
printf("%d\n", increment());
// (unfortunately) x is not available here...
}
Returns:
1
2
3
每次调用increment()
function 时,它会返回一个更大的数字。
不能在 scope 之外使用变量。 因此,您可以在“全局范围”中定义一个变量(如Kerrek SB 所示)或在 function (或任何其他范围)中定义一个 static 变量(如上所示)。 如果这些可能性中的任何一种不适用于您的情况,恐怕您应该(彻底)修改您的应用程序的结构......
C 不是动态语言 - 所有声明的变量始终存在(受范围规则约束)。
您无法测试是否已声明变量,这是编译器的工作,如果您尝试使用不在 scope 中的变量,它会给您一个错误。
首次加载程序时,全局变量会自动为它们分配空间(在“数据”段中)。
因此,您只能测试变量是否已从其原始分配值发生变化。
There is no way You can restrict scope of global variable to one function in file,It is available to all the functions in a file,However You can restrict the scope of global variable to a file only, by using static keyword with global variable name .
file1.c //1st file file2.h //2nd file
#include<file2.h>
main() static int a;
{
fun(); fun()
} {
printf("%d",a);
}
在示例中,您确实有两个文件 file1.c 和 file2.h,现在变量 a 可用于 function fun() 仅在第一个文件中。
将其声明为全局 static 并且不要初始化它。 只要调用 function 就在 function 内初始化它
IE
static int a;
void main()
{
// Some code here
}
void function()
{
a=10;
// Some code here as well
}
建议尽量避免使用全局变量。 在您的特定情况下,您可以做的只是:
function(int* toModify)
{
*toModify = 10;
// do sth
}
现在您的其他功能可以使用修改后的值。
但是,如果您热衷于使用全局变量,则必须使用两个全局变量,
int gIsFuncCalled = 0;
int gToModify = 0;
void function()
{
gIsFuncCalled = 1;
gToModify = 10;
}
现在您可以使用gToModify
有条件地使用gIsFuncCalled
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.