25

我正在阅读一些关于externs的信息。现在作者开始提到变量声明和定义。通过声明,他提到了以下情况:如果声明了变量,则未为其分配空间。现在这让我感到困惑,因为我认为大多数时候我在 C 中使用变量时,我实际上是在定义和声明它们对吗?IE,

int x; // definition + declaration(at least the space gets allocated for it)

我认为只有在 C 中声明变量但未定义变量时才使用:

extern int x; // only declaration, no space allocated

我做对了吗?

4

3 回答 3

23

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

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 标准中所写的那样,声明指定了一组标识符的解释和属性以及对象的定义,从而为该对象保留存储空间。标识符的定义也是该标识符的声明

于 2013-10-11T20:40:34.977 回答
0

这就是我如何看待它,将我在互联网上找到的点点滴滴放在一起。我的观点可能是歪曲的。
一些基本的例子。

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.                                     .
于 2016-10-15T04:48:04.503 回答
0

在声明期间,内存位置由该变量的名称保留,但在定义期间,内存空间也分配给该变量。

于 2018-02-07T10:41:45.277 回答