变量声明与定义

22 c

我正在阅读关于外部的一些信息.现在作者开始提到变量声明和定义.通过声明,他提到了以下情况:如果声明了变量,则不分配它的空间.现在,这给我带来了困惑,因为我认为科技部的时代,当我使用C变量,我其实都定义和声明他们的权利?即

int x; // definition + declaration(at least the space gets allocated for it)
Run Code Online (Sandbox Code Playgroud)

我认为当你使用时,只有当你声明变量而不是定义它时C中的情况是:

extern int x; // only declaration, no space allocated
Run Code Online (Sandbox Code Playgroud)

我做对了吗?

oua*_*uah 19

基本上,是的,你是对的.

extern int x;  // declares x, without defining it

extern int x = 42;  // not frequent, declares AND defines it

int x;  // at block scope, declares and defines x

int x = 42;  // at file scope, declares and defines x

int x;  // at file scope, declares and "tentatively" defines x
Run Code Online (Sandbox Code Playgroud)

如C标准所述,声明指定一组标识符的解释和属性以及对象的定义,从而导致为该对象保留存储.标识符定义也是该标识符的声明.

  • @hackks你不应该相信来自互联网的一些低质量文本.引用是错误的.你不能在C和`x = 10中多次定义一个对象;`是一个执行赋值而不是定义的语句. (5认同)