2012-12-27 114 views
0

爲什麼我的normals_since函數看不到我的全局變量會跳躍? 我不能相信在main中聲明的變量在整個程序中是不可用的,那就是封裝或隱藏什麼的意思?是否可以像main.z或_ main _z這樣的祕密方式訪問? 我的gcc錯誤>>C函數看不見全局變量

yrs_since.c: In function ‘normals_since’: 
yrs_since.c:40:9: error: ‘leaps’ undeclared (first use in this function) 
yrs_since.c:40:9: note: each undeclared identifier is reported only once </p> 
for each function it appears in 

possible answer 
looks like if I want all functions to see the vars, I have to move 
int z; //place holder 
int leaps; 
int normals; 

的主要之外,在頂部他們宣佈了#define語句

#include stdio.h> 
#include stdlib.h> 
#define START_GREG 1582 
int yrs_since(int year); //type-declare the function 
int leaps_since(int years); 
int normals_since(int years); 

int main(int argc, char* argv[]){ 
    int year = 1599; //local var 
    int z; //place holder 
    int leaps; 
    int normals; 
    z = yrs_since(year); //call the function 
    leaps = leaps_since(z); //leap years move the doomsday fwd by 2 days 
    normals= normals_since(z); //normal years it adjusts one day 
    printf("blah blah %d,", z);//print the result 
    printf("leap years since 1582:-->> %d <<", leaps); 
    printf("normal years since 1582:-->> %d <<", normals); 
    return EXIT_SUCCESS; 
} 
int yrs_since(year){ 
    int x; 
    x=year-START_GREG; 
    return x; 
}; 
int leaps_since (years){ 
    return years/4; 
}; 

int normals_since(years){ 
    int x; 
    x=years-leaps; 
    return x; 
}; 
+1

'leaps'甚至不是一個全局變量。 – nhahtdh

+0

不要沒有終止函數的定義與';'尾'}'後,它是無效的C. – ouah

+0

您可能希望你的問題格式化到的東西是更可讀的,只有代碼的相關部分,並明確了哪些代碼在哪個源文件中。 – che

回答

3

權利,因爲你已經發現了,在函數變量是隻對功能可見。 main是一個函數,就像任何其他函數一樣,它不會以任何特殊方式處理。

全局變量對外宣稱的功能(但它總體上是好的建議,以避免全球性的功能,在一般。

的解決方案,如果你想避免全局變量,是從主傳遞變量到函數使用變量

例如:。

int normals_since(int years, int leaps){ 
    int x; 
    x=years-leaps; 
    return x; 
}; 

請注意,我說「INT」的歲月變量雖然老C風格,仍然允許在某些編譯器,它肯定推薦使用ANSI標準(加-ansi -strict -Wall -std=c99你的gcc命令行給你警告,「事情可能做錯了」和錯誤不遵循ANSI標準)

0

可能的答案後: 看起來像如果我想所有的功能看瓦爾,我必須移動

int z; //place holder 
int leaps; 
int normals; 

主要以外,並宣佈他們在#defines之後的頂部。

2

main()中聲明的變量是可見的只有main()本身。您可能需要將這些變量移入全局範圍(所有函數之外)或將指針傳遞給其他函數。

0

在塊內聲明的任何var未定義在塊的外面。
沒有什麼可相信的,它是它的工作方式(也用其他編程語言)。
如果您想要全球var - 在所有塊之外聲明它。

1

因爲你定義了飛躍的功能main()身體。如果你希望它是真正的全球性,它定義了main()功能之外,例如,對原型如下:

int normals_since(int years);