黑马程序员技术交流社区
标题: 关于全局变量和局部变量的问题 [打印本页]
作者: sen 时间: 2014-4-12 22:19
标题: 关于全局变量和局部变量的问题
本帖最后由 sen 于 2014-5-20 11:58 编辑
#include <stdio.h>
int age;
void test()
{
int age;
age =10;
}
int main()
{
printf("%d\n",age);//0
int age = 20;
printf("%d\n",age);//20
test(); //(为什么这句函数没有调用? 如没有int age = 20 则能调用)
printf("%d\n",age);//20
return 0;
}
为什么main函数中的test函数对之后的printf没有影响??
作者: 星河鹭起 时间: 2014-4-12 22:31
void test()
{
int age;
age =10;
}
这个函数里定义的age作用域只在此函数,也就是说这个age=10只在这个函数里有用,一旦函数被调用完,age=10就不再存在了,在内存中消失了。
主函数中test()函数调用了一次,因此当此函数调用完毕后,age=10,就会在内存中消失。由于你已经在主函数中定义了age=20,因此在输出的时候会寻找age的值,因此age=10已经消失了,所以会输出age=20;并不是test()函数没有进行调用。如果你在test()函数里增加输出age的值,就会发现age=10,还是输出了,test()函数被调用了、
作者: 2014571245 时间: 2014-4-13 03:41
- #include <stdio.h>
- int age;
- void test()
- {
- int age;
- age =10;
- [color=Red] printf("调用了test的函数\n");[/color]
- }
- int main()
- {
- printf("%d\n",age);//0
- int age = 20;
- printf("%d\n",age);//20
- test();
- printf("%d\n",age);//20
- return 0;
- }
复制代码
结果为:
0
20
调用了test的函数
20
test()函数肯定是调用了,但是test()里的age是局部变量,只在test函数内部有效,其实只是局部变量和全局变量同名而已,test里的age你可以改为x或y任意变量名,不会对main造成影响;其次,在main函数中你传的是个空值,如果是地址的话就会对main函数的printf有影响,也可以简单的理解为是地址传递与值传递的区别吧!!
作者: 李烨 时间: 2014-4-13 10:49
int main()
{
printf("%d\n",age);//0
int age = 20;
printf("%d\n",age);//20
test(); //(为什么这句函数没有调用? 如没有int age = 20 则能调用)
printf("%d\n",age);//20
return 0;
}
***********************************
main函数中的调用test()时,会为test()函数分配一个内存空间,但是test()函数掉用完之后这个test内存空间会被删掉,包括里面的变量,全局变量int a与test里的局部变量int a在不同的内存空间中,作用域不同,没有联系。
作者: 杨晓斌 时间: 2014-4-13 13:14
变量分为全局变量和局部变量,全局变量是声明在函数之外的,任意函数都可以调用,而局部变量是声明在函数内部的之恩那个在本函数调用,在别的函数里是没用作用,也就是他的作用域。
#include <stdio.h>
int age;
void test()
{
int age;
age =10;
}
int main()
{
printf("%d\n",age);//0
int age = 20;
printf("%d\n",age);//20
test(); //(为什么这句函数没有调用? 如没有int age = 20 则能调用)
printf("%d\n",age);//20
return 0;
}
虽然你声明了全局变量age,但是在test函数中调用的还是自己本身的局部变量age,赋值给他这个局部变量是10,和主函数的age是没有关系的,而且不会传值,所以得到的结果还是0.20
作者: 从┧靇┟开始 时间: 2014-4-13 15:48
#include <stdio.h>
int age;
void test()
{
int age; // int给age分配了内存,{}代码块内部运行完毕该部分内存就消失了 。若是没有int age则会把10赋值给全局变量age,依然不会影响输出。
age =10;
}
int main()
{
printf("%d\n",age);//0
int age = 20;
printf("%d\n",age);//20
test(); //
printf("%d\n",age);//20
return 0;
}
作者: 戴文婷 时间: 2014-4-14 02:21
- #include <stdio.h>
- int age;//这个是全局变量。
- void test()
- {
- int age;//这个是test函数的局部变量,出了函数就会被释放
- age =10;
- }
- int main()
- {
- printf("%d\n",age);//0
-
- int age = 20;//这里还包含了一个main函数中的 age局部变量。
-
- printf("%d\n",age);//20
-
- test(); //(为什么这句函数没有调用? 如没有int age = 20 则能调用)特地试过了。去掉int age=20的话,输出结果就全部是0
-
- printf("%d\n",age);//20
-
- return 0;
- }
复制代码
test 中的变量周期只有test内执行完了,出了函数就被释放掉了。所以后面的变量没有变成10
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |