[英]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.