所以我一直在努力自学C。所以我身边只有几个视频和文章,还有一本书。虽然这听起来像一个简单的概念(我相信它是),但我不认为这个概念是明确的。
当一个变量被声明为或时,你能引用一个例子吗?
就像我在一些文章或论坛上看到的
Int;(x声明)
在某个地方写的
Int;(x被定义).
何时将内存分配给变量?同样,在某个地方,有人说必须先定义变量才能得到内存分配,而在某个地方,它是在声明变量时分配的?
发布于 2020-10-24 08:09:49
就像我读过的一些文章或论坛一样,他们说Int;(x是声明的)某个地方,它是写的Int;(x是定义的)。
实际上,int x;同时声明和定义它,因此两者都是有效的,但不完整。
声明显示编译器没有创建变量的类型。
extern int x; // <- this is declaration如果对象是在定义之前声明的,则定义将创建该对象。
extern int x;
int x;是有效的但是
extern int x;
double x; 不是。
发布于 2020-10-24 07:47:59
我希望这能给您提供一个关于变量何时被声明、分配、初始化、解除分配和消失(销毁)的简要概述。
/* 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;
}https://stackoverflow.com/questions/64495515
复制相似问题