为什么我的normals_since函数看不到我的全局变量跳跃? 我无法相信在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之外,并在#defines
之后将它们声明在顶部#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;
};
答案 0 :(得分:3)
是的,正如您所知,函数INSIDE只对该函数可见。 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的错误标准)
答案 1 :(得分:2)
main()
中声明的变量仅显示 到main()
本身。您需要将这些变量移动到全局范围内(在所有函数之外)或将指针传递给其他函数。
答案 2 :(得分:1)
因为您已在内部定义了跳跃函数体main()
。如果您希望它真正全球化,请在main()
函数之外定义它,例如,在原型的正下方:
int normals_since(int years);
答案 3 :(得分:0)
可能的答案: 看起来如果我希望所有功能都能看到变量,我必须移动
int z; //place holder
int leaps;
int normals;
在main之外,并在#defines
之后在顶部声明它们。
答案 4 :(得分:0)
块内声明的任何var
都没有在块的旁边定义
没有什么可以相信的,它的工作方式(也在其他编程语言中)
如果你想要一个全局var
- 在所有块之外声明它。