简体   繁体   English

如何声明仅存在于一个 function 中的全局变量?

[英]How to declare a global variable which is present in only one function?

I need to declare a global variable which is only available if a certain function is called.我需要声明一个全局变量,该变量仅在调用某个 function 时可用。 If that function is not called than that variable should not be available.如果没有调用该 function ,则该变量不应该可用。

 void function()
 {
   // if this function is called then declare int a=10; 
   // as global so other function can use this 
 }

How can I do such a thing in c?我怎么能在 c 中做这样的事情?

C doesn't work like that - a global variable is allocated at load time and exists for the entire duration of the program, independent of the runtime behaviour. C 不能那样工作 - 全局变量在加载时分配,并在程序的整个持续时间内存在,与运行时行为无关。 If you really must know whether the variable has been "set", you could include a separate flag:如果您真的必须知道变量是否已“设置”,您可以包含一个单独的标志:

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) { /* ... */ }
}

If you know that your variable can only be non-negative, then you could alternatively use a special sentinel value like -1 to indicate that the variable hasn't been "set" yet.如果您知道您的变量只能是非负数,那么您也可以使用像-1这样的特殊标记值来指示该变量尚未“设置”。

Most likely though is that you should rework your design so that you already know by other means whether or not you need the variable.但最有可能的是,您应该重新设计您的设计,以便您已经通过其他方式知道您是否需要该变量。

You can define a static variable inside a function, then it is only available in that function (and keeps its value between multiple calls):您可以在 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

Each time the increment() function is called, it will return a higher number.每次调用increment() function 时,它会返回一个更大的数字。

It is not possible to use variables outside it scope.不能在 scope 之外使用变量。 So you could either define a variable in the 'global scope' (as demonstrated by Kerrek SB ) or a static variable in a function (or any other scope) (as demonstrated above).因此,您可以在“全局范围”中定义一个变量(如Kerrek SB 所示)或在 function (或任何其他范围)中定义一个 static 变量(如上所示)。 If any of these possibilities are not to applicable for your situation, I am afraid you should (drastically) modify the structure of you application...如果这些可能性中的任何一种不适用于您的情况,恐怕您应该(彻底)修改您的应用程序的结构......

C is not a dynamic language - all declared variables exist (subject to scoping rules) at all times. C 不是动态语言 - 所有声明的变量始终存在(受范围规则约束)。

You cannot test whether a variable has been declared , that's the compilers job, and it'll give you an error if you try to use one that's not in scope.您无法测试是否已声明变量,这是编译器的工作,如果您尝试使用不在 scope 中的变量,它会给您一个错误。

Global variables have space allocated for them (in the "data" segment) automatically when the program is first loaded.首次加载程序时,全局变量会自动为它们分配空间(在“数据”段中)。

Hence you can only test whether the variable has changed from its original assigned value.因此,您只能测试变量是否已从其原始分配值发生变化。

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. 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);
                                          }

In the example you do have two files file1.c and file2.h,Now variable a is available to function fun() only in 1st file.在示例中,您确实有两个文件 file1.c 和 file2.h,现在变量 a 可用于 function fun() 仅在第一个文件中。

declare it global as static and dont initialize it.将其声明为全局 static 并且不要初始化它。 as soon as the function is called initialize it inside the function只要调用 function 就在 function 内初始化它

ie IE

static int a;

void main()
{
  // Some code here
}

void function()
{
  a=10; 
  // Some code here as well

}

It is recommended to avoid use of global variables as far as possible.建议尽量避免使用全局变量。 In your particular case what you can do is simply:在您的特定情况下,您可以做的只是:

function(int* toModify)
{
    *toModify = 10;
    // do sth
}

Now your other functions can use the modified value.现在您的其他功能可以使用修改后的值。

However, if you are keen on using a global variable, you have to use two global vars,但是,如果您热衷于使用全局变量,则必须使用两个全局变量,

int gIsFuncCalled = 0;
int gToModify = 0;

void function() 
{ 
    gIsFuncCalled = 1;
    gToModify = 10;
}

Now you can use gToModify conditionally using gIsFuncCalled现在您可以使用gToModify有条件地使用gIsFuncCalled

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM