[英]Variable declaration vs definition
我正在阅读关于外部的一些信息。 现在作者开始提到变量声明和定义。 通过声明,他提到了以下情况:如果声明了变量,则不分配它的空间。 现在,这给我带来了困惑,因为我觉得很多时候,当我使用C变量,我其实都定义和声明他们的权利? 即
int x; // definition + declaration(at least the space gets allocated for it)
我认为当你使用时, 只有当你声明变量而不是定义它时C中的情况是:
extern int x; // only declaration, no space allocated
我做对了吗?
基本上,是的,你是对的。
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
如C标准所述,声明指定一组标识符的解释和属性以及对象的定义,从而导致为该对象保留存储 。 标识符的定义也是该标识符的声明 。
这就是我如何看待它在互联网上找到的点点滴滴。 我的观点可能是歪曲的。
一些基本的例子。
int x;
// The type specifer is int
// Declarator x(identifier) defines an object of the type int
// Declares and defines
int x = 9;
// Inatializer = 9 provides the initial value
// Inatializes
C11标准6.7状态标识符的定义是该标识符的声明:
- 对于一个对象,导致为该对象保留存储;
- 对于一个功能,包括功能体;
int main() // Declares. Main does not have a body and no storage is reserved
int main(){ return 0; }
// Declares and defines. Declarator main defines
// an object of the type int only if the body is included.
下面的例子
int test(); Will not compile. undefined reference to main
int main(){} Will compile and output memory address.
// int test();
int main(void)
{
// printf("test %p \n", &test); will not compile
printf("main %p \n",&main);
int (*ptr)() = main;
printf("main %p \n",&main);
return 0;
}
extern int a; // Declares only.
extern int main(); //Declares only.
extern int a = 9; // Declares and defines.
extern int main(){}; //Declares and defines. .
在声明期间,内存位置由该变量的名称保留,但在定义期间,内存空间也分配给该变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.