600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 全局变量和extern详解

全局变量和extern详解

时间:2021-02-22 05:20:12

相关推荐

全局变量和extern详解

php教程|PHP开发

全局变量 extern

php教程-PHP开发

婚纱摄影网站模版整站源码,ubuntu怎么加硬盘,tomcat部署服务器,爬虫网站数据,php输入数字的平方,秋天seolzw

声明与定义

视频编辑源码,ubuntu常用安装源,tomcat一直崩溃,爬虫正则使用,php http如何判断缓存,nuxt seolzw

首先讲一下声明与定义

table源码,ubuntu登录后卡死,tomcat自动删除旧日志,门缝爬虫白色,28学php,浙江智能化seo优化答疑解惑lzw

声明不等于定义,声明只是指出了变量的名字,并没有为其分配存储空间;定义指出变量名字同时为变量分配存储空间,定义包含了声明

extern int i; //声明变量i,但没分配存储空间,还不能使用, 可以出现很多次,下面的三种情况只能出现一次

int i; //定义了变量i,并分配了空间,可以使用

extern int a =0 //定义一个全局变量a 并给初值

int a =0;//定义一个全局变量a,并给初值

注意:在程序中一个变量可以声明多次,但只能定义一次。

全局变量:在函数内部定义的变量称为局部变量,它的作用域是从定义处到函数结束;在函数外部定义的称为全局变量,它的作用域是从定义处直到文件结束。

不管是全局变量还是局部变量,作用域都是从定义处开始的

extern

extern是用来声明全局变量的

#includeusing namespace std;int main(){ extern int a; cout<<a<<endl; //int a=5; this is wrong , a should be a global variable getchar(); return 0;}int a=5;//global variable

用#include可以包含其他头文件中变量、函数的声明,为什么还要extern关键字?如果我想引用一个全局变量或函数a,我只要直接在源文件中包含#include (xxx.h包含了a的声明)不就可以了么,为什么还要用extern呢?

test.h

#includeusing namespace std;int changea();//int temp2=1; 如果在此定义temp2的情况下,main.cpp和test.cpp都包含了test.h,会造成temp2的重复定义 extern int temp3;

test.cpp

#include "test.h"int temp1=1000;//int temp2=10; 如果不注释掉会出错 int temp3=100;extern const int temp4=400;

main.cpp

#include #include #include "test.h"using namespace std;int main(int argc, char *argv[]){ extern int temp1; cout<<"temp1 is"<<temp1<<endl; extern int temp4; cout<<"temp4 is"<<temp4<<endl; //extern int temp2; //cout<<"temp2 is"<<temp2<<endl; cout<<"temp3 is"<<temp3<<endl; system("PAUSE"); return EXIT_SUCCESS;}

output:

temp1 is1000

temp4 is400

temp3 is100

temp1: 在test.cpp中声明 int temp1=1000, 在main.cpp中使用temp1,首先声明temp1是一个外部变量

temp2:在test.h中定义,main.cpp和test.cpp都包含了test.h,会造成temp2的重复定义,注释掉程序才能通过编译

temp3:在test.h中声明,在test.cpp中定义,在main.cpp中使用

temp4:const默认是局部变量,即使是在全局中申明也一样,且在定义时,必须赋予初值。若想在外部引用,必须加extern

总之原则就是:要想使用其他文件的一个全局变量,就必须定义extern type variablename,然后才能使用

如果const变量想被其他文件使用,在定义的前面需要添加extern

更多全局变量和extern详解相关文章请关注PHP中文网!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。