既然函数看到全局变量跳跃,为什么我的法线不能??
我不敢相信main中声明的变量在整个程序中都是不可用的,这是什么封装、隐藏或者什么意思?它是以某种秘密的方式访问的,比如main.z或_main_z??
我的gcc错误>>
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;
在main之外,在定义
#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;
};
最佳答案
好吧,正如您所发现的,函数中的变量只对该函数可见。main
是一个函数,与任何其他函数一样,它不以任何特殊方式处理。
全局变量是在函数之外声明的(但一般来说,最好避免全局函数)。
如果要避免全局变量,解决方案是使用变量将变量从main传递到函数中。
例如:
int normals_since(int years, int leaps){
int x;
x=years-leaps;
return x;
};
注意,我在years变量中添加了“int”。虽然在某些编译器中仍然允许使用旧式C,但绝对建议使用ANSI标准(在gcc命令行中添加
-ansi -strict -Wall -std=c99
以警告您“可能做错的事情”和不遵循ANSI标准的错误)关于c - C函数看不到全局变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14055507/