变量定义与声明概念辨析与区别.docVIP

  • 11
  • 0
  • 约7.16千字
  • 约 7页
  • 2017-03-09 发布于江苏
  • 举报
变量定义与声明概念辨析与区别

关于定义与声明 例如:在主函数中int main() { extern int A; //这是个声明而不是定义,声明A是一个已经定义了的外部变量 //注意:声明外部变量时可以把变量类型去掉如:extern A; dosth(); //执行函数} int A; //是定义,定义了A为整型的外部变量(全局变量)外部变量(全局变量)的定义与外部变量的声明是不相同的,外部变量的定义只能有一次,它的位置是在所有函数之外,而同一个文件中的外部变量声明可以是多次的,它可以在函数之内(哪个函数要用就在那个函数中声明)也可以在函数之外(在外部变量的定义点之前)。系统会根据外部变量的定义(而不是根据外部变量的声明)分配存储空间的。对于外部变量来讲,初始化只能是在定义中进行,而不是在声明中。所谓的声明,其作用,是声明该变量是一个已在后面定义过的外部变量,仅仅是在为了提前引用该变量而作的声明而已。extern只作声明,不作定义。 用static来声明一个变量的作用有二: (1) 对于局部变量用static声明,则是为该变量分配的空间在整个程序的执行期内都始终存在(2) 外部变量用static来声明,则该变量的作用只限于本文件模块 Declarations and Definitions As well see in Section 2.9 (p. 67), C++ programs typically are composed of many files. In order for multiple files to access the same variable, C++ distinguishes between declarations and definitions. 就像我们在2.9 (p. 67)节看到的一样,典型的C++程序通常会由好多文件组成。为了使不同的文件都可以访问同一个变量,C++会区分变量的声明(declarations)和定义(definitions)。 A definition of a variable allocates storage for the variable and may also specify an initial value for the variable. There must be one and only one definition of a variable in a program. 变量的定义(definitions)会为这个变量分配存储空间,并且可能会为其指定一个初始化的值。在程序里,一个变量必须有一个,也只能有一处定义(definitions)。 A declaration makes known the type and name of the variable to the program. A definition is also a declaration: When we define a variable, we declare its name and type. We can declare a name without defining it by using the extern keyword. A declaration that is not also a definition consists of the objects name and its type preceded by the keyword extern: 变量的声明(declarations)会将变量的类型和名称传达给程序。当然,定义(definitions)也是一种声明:当我们定义一个变量的时候,我们当然也声明了他的名称和类型。我们可以通过使用“extern”关键字来声明(declarations)一个变量,而不用定义(definitions)它。声明(declarations)的形式就是在对象(变量)的名字和类型前面,加上关键字“extern”: extern int i; // declares but does not define i int i; // declares and defines i An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be d

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档