C中变量声明和定义之间的区别什么时候分配内存?

问题描述

所以我一直在尝试自己学习C。因此,在我身边只有几个视频和文章以及一本书。尽管这听起来像是一个简单的概念(我敢肯定是这样),但我认为这个概念对我来说很清楚。

当变量是 声明的 定义的 时,能否请您举一个例子?

就像我在阅读某些文章或论坛时所说的

整数x; (已声明x)

写的地方

整数x; (定义了x)。

内存何时分配 ? 再次有人说必须先定义变量才能分配内存,而有人说在声明变量时分配变量?

解决方法

我希望这能为您简要介绍何时声明,分配,初始化,释放和消失(销毁)变量。

/* global variable A declared and memory for int is allocated */
/* memory will only be unallocated at global program exit */
/* global variable A initialized/defined with value 10 */
int A = 10;

void test(int D){
    /* function test is called by main with argument test(5) */
    /* local variable D is declared,memory for int is allocated */
    /* and initialized with value 5 */
    
    /* add local variable D to global variable A */
    A = A + D;
    
    /* after this point,local variable D will be deallocated */
    /* and will vanish */
}

int main(int argc,char *argv[]){
    /* local variable B declared,memory for int allocated */
    /* and initialized with value 20 */
    int B = 20;
    
    {
        /* local scoped variable C declared,memory for int allocated */
        /* and initialized with value 30 */
        int C = 30;
        /* after this point,local scoped variable C will be */
        /* deallocated and will vanish */
    }
    
    /* 5 is a local scoped const of size int,memory will be allocated */
    test(5);
    /* after this point,local scoped const 5 will be deallocated */
    /* and will vanish */
    
    
    /* after this point,local variable B will be deallocated */
    /* and will vanish */
    return A;
}
,

就像我在某些文章或论坛中读到的那样 整数x; (x被声明) 它写的某个地方 整数x; (x已定义)。

实际上,int x;同时声明和定义了它们,因此两者都是有效的,但是不完整。

该声明显示编译器未创建变量的类型。

extern int x; // <- this is declaration

如果对象在其定义必须与声明匹配之前被声明,则定义将创建对象。

extern int x;
int x;

有效,但

extern int x;
double x; 

不是。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...