欢迎来到天天文库
浏览记录
ID:8981172
大小:28.33 KB
页数:2页
时间:2018-04-13
《[二级c语言]c语言中定义与声明的区别》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、未来教育考试网www.eduexam.cn刚学C语言的时候,我甚至都没有听过声明和定义,根本不知道它们到底有什么联系,老师在课堂上也没有解释两者的区别。我在网上搜到了经典作品《Cprimerplus》的原版资料,顺便翻译了一下,同时附上我自己的见解。变量在定义时被分配内存,并且变量可以指定一个初始化的值。变量只能在这个程序中定义一次。声明在该程序中指定了变量的类型和名称。定义也是一种声明:当我们定义一个变量时,我们声明了它的名字和类型。我们也可以通过使用extern关键字来声明一个变量的名字而不用定义。一个声明可以是加extern前缀的并包含了目标的类型和名称,如:点击(
2、此处)折叠或打开externinti;//声明了i但是并未定义inti;加extern关键字的声明不是定义并且不分配内存(实际上声明是不分配内存的)。实际上,它只是宣称了已经在其它文件中定义的变量的名称和类型。一个变量可以声明多次,但是只能定义一次。声明只有在他同样是定义时才能初始化,因为只有定义才会分配内存。如果一个声明初始化,那么它就被当做定义,即便已经被extern标记,例如点击(此处)折叠或打开externdoublepi=3.1416;//定义尽管使用了extern,它还是定义了pi.该变量分配了内存并初始化。只有出现在函数的extern声明才可能初始化。因为被
3、当做定义,所以后续的任何对该变量的定义都是错误:点击(此处)折叠或打开externdoublepi=3.1416;//定义doublepi;//错误:重定义pi我对定义和声明的认识是:定义给变量分配了内存,并且只能定义一次,如inti=0;声明没有给变量分配内存,可以声明多次,最常用的是函数参数的声明如voidmain(inta,intb);这里面的a和b都未分配内存,只是说明了变量的名称和数据类型。注:《CPrimerPlus》上的原文资料Adefinitionofavariableallocatesstorageforthevariableandmayalsospec
4、ifyaninitialvalueforthevariable.Theremustbeoneandonlyonedefinitionofavariableinaprogram.Adeclarationmakesknownthetypeandnameofthevariabletotheprogram.Adefinitionisalsoadeclaration:Whenwedefineavariable,wedeclareitsnameandtype.Wecandeclareanamewithoutdefiningitbyusingtheexternkeyword.Adecl
5、arationthatisnotalsoadefinitionconsistsoftheobject'snameanditstypeprecededbythekeywordextern:externinti;//declaresbutdoesnotdefineiinti;//declaresanddefinesiAnexterndeclarationisnotadefinitionanddoesnotallocatestorage.Ineffect,itclaimsthatadefinitionofthevariableexistselsewhereintheprogra
6、m.Avariablecanbedeclaredmultipletimesinaprogram,butitmustbedefinedonlyonce.Adeclarationmayhaveaninitializeronlyifitisalsoadefinitionbecauseonlyadefinitionallocatesstorage.Theinitializermusthavestoragetoinitialize.Ifaninitializerispresent,thedeclarationistreatedasadefinitionevenifthedeclar
7、ationislabeledextern:externdoublepi=3.1416;//definitionDespitetheuseofextern,thisstatementdefinespi.Storageisallocatedandinitialized.Anexterndeclarationmayincludeaninitializeronlyifitappearsoutsideafunction.Becauseanexternthatisinitializedistreatedasadefinition,anys
此文档下载收益归作者所有