第十二周 项目一(2)

来源:互联网 发布:印刷照片淘宝 编辑:程序博客网 时间:2024/05/28 14:56

阅读下面有全局变量的程序,掌握全局变量的存储特征,必要时单步调试综合理解。

代码2:

#include <iostream>using namespace std;void cude();int main(){    extern int x;//去掉extern及本行全删除会怎样?    x=5; //去掉这一句呢?    cude();    cout<<x<<endl;    return 0;}int x=10;void cude(){    x=x*x*x;}


运行结果:

预计运行结果:125

实际运行结果:125

extern声明x后,x变为全局变量,第六行是声名变量,第十二行是定义变量当经过第六行后x值为10,经过第七行x变为5,调用到函数cude中x值变为125,虽然void函数不反馈值,由于x为全局变量,x已赋值为125,所以输出结果是125.

***去掉extern代码及运行结果:

#include <iostream>using namespace std;void cude();int main(){    int x;    x=5; //去掉这一句呢?    cude();    cout<<x<<endl;    return 0;}int x=10;void cude(){    x=x*x*x;}


经过单步调试,去掉extern之后,x不再是全局变量,x值首先为5,到调用函数cude中时,x值为10,经过运算得到1000,但函数值不反馈,返回主函数x值为5,最后输出5.

***去掉"extern int x;"的代码及结果:

#include <iostream>using namespace std;void cude();int main(){    x=5; //去掉这一句呢?    cude();    cout<<x<<endl;    return 0;}int x=10;void cude(){    x=x*x*x;}


结果:

知识点总结:x变量未声明,出错!!

***去掉"x=5"这一行的代码及运行结果:

#include <iostream>using namespace std;void cude();int main(){    extern int x;    cude();    cout<<x<<endl;    return 0;}int x=10;void cude(){    x=x*x*x;}

运行结果:

知识点总结:当去掉x=5时,由extern全局变量的x赋值为10,再经过cude函数的调用,得x=1000.

 

0 0
原创粉丝点击