如何声明一个仅出现在一个函数中的全局变量?

发布于 2024-11-29 13:59:43 字数 233 浏览 0 评论 0原文

我需要声明一个全局变量,该变量仅在调用某个函数时才可用。 如果未调用该函数,则该变量不应该可用。

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

我怎样才能在c中做这样的事情?

I need to declare a global variable which is only available if a certain function is called.
If that function is not called than that variable should not be available.

 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

昇り龍 2024-12-06 13:59:43

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< /code> 表示该变量尚未“设置”。

但最有可能的是,您应该重新设计您的设计,以便您已经通过其他方式知道是否需要该变量。

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. 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.

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.

星星的轨迹 2024-12-06 13:59:43

您可以在函数内定义静态变量,然后它仅在该函数中可用(并在多次调用之间保留其值):

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() 函数调用时,它将返回一个更大的数字。

无法在其范围之外使用变量。因此,您可以在“全局范围”中定义一个变量(如 Kerrek SB)或函数(或任何其他作用域)中的静态变量(如上所示)。如果这些可能性中的任何一个不适用于您的情况,恐怕您应该(彻底)修改您的应用程序的结构......

You can define a static variable inside a function, then it is only available in that function (and keeps its value between multiple calls):

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.

It is not possible to use variables outside it 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). If any of these possibilities are not to applicable for your situation, I am afraid you should (drastically) modify the structure of you application...

誰認得朕 2024-12-06 13:59:43

C 不是动态语言 - 所有声明的变量始终存在(遵守范围规则)。

您无法测试变量是否已声明,这是编译器的工作,如果您尝试使用不在范围内的变量,它会给您一个错误。

首次加载程序时,全局变量会自动为其分配空间(在“数据”段中)。

因此,您只能测试变量是否已从其原始指定值更改。

C is not a dynamic language - all declared variables exist (subject to scoping rules) at all times.

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.

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.

祁梦 2024-12-06 13:59:43

您无法将全局变量的范围限制为文件中的一个函数,它可用于文件中的所有函数,但是您可以通过使用带有全局变量名称的 static 关键字将全局变量的范围限制为仅一个文件。

   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 仅可在第一个文件中用于 fun() 函数。

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.

对不⑦ 2024-12-06 13:59:43

建议尽可能避免使用全局变量。
在您的特定情况下,您可以做的很简单:

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

现在您的其他函数可以使用修改后的值。

但是,如果您热衷于使用全局变量,则必须使用两个全局变量,

int gIsFuncCalled = 0;
int gToModify = 0;

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

现在您可以使用 gIsFuncCalled 有条件地使用 gToModify

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

挽你眉间 2024-12-06 13:59:43

将其声明为全局静态并且不初始化它。
一旦调用该函数,就在函数内部对其进行初始化,

static int a;

void main()
{
  // Some code here
}

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

}

declare it global as static and dont initialize it.
as soon as the function is called initialize it inside the function

i.e.

static int a;

void main()
{
  // Some code here
}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文