问题及代码1:
#include <iostream>
using namespace std;
int a=3, b=5;
int max(int a, int b)
{
int c;
c=a>b? a:b;
return c;
}
int main()
{
int a=8;
cout<<max(a,b)<<endl;
return 0;
}
运行结果1:
如果在main函数中没有(int a=8),运行结果:
问题及代码2:
#include <iostream>
using namespace std;
void cude();
int main()
{
extern int x;
x=5;
cude();
cout<<x<<endl;
return 0;
}
int x=10;
void cude()
{
x=x*x*x;
}
运行结果2:
如果在main函数中,没有( x=5)运行结果:
如果在main函数中,没有(entern)运行结果:
知识点总结:
在函数内定义的变量是局部变量,而在函数之外的变量是外部变量,称为全局变量,增加了函数间数据联系的渠道。
学习心得:
第一个代码中,在开始就声明变量,a=3,b=5,如果在main函数中没有声明x=8,那么a的值就会默认为3。第二个代码中,用entern对x提前引用声明,如果没有entern就无法调用void cude函数,使得最后x=5。如果没有在main函数中声明变量x=5,那么entern就会调用x=10,使最后答案变成1000.
本文通过两个示例探讨了C++中全局变量与局部变量的概念及其使用方式。重点介绍了如何在不同函数间共享数据,并解释了外部变量的声明与初始化过程。

被折叠的 条评论
为什么被折叠?



