简体   繁体   English

初始化局部变量的值在C中的堆栈之前存储在哪里?

[英]Where is an initialized local variable's value stored before the stack in C?

I have a question about local variables. 我对局部变量有疑问。 I am well aware that during a function call, the memory for the variable is allocated and after returning from the function, the memory is freed up. 我很清楚,在函数调用期间,将为变量分配内存,并且从函数返回后,将释放内存。 But from where does the program know what value to use during initialization? 但是程序从哪里知道初始化期间要使用什么值?

void foo()
{
  uint8_t x = 2u;
}

So my question is, where is the value 2 stored in the memory before calling the function? 所以我的问题是,在调用函数之前,值2在哪里存储在内存中? My guess that it is in the text segment (in the non volatile memory) and is read from there to stack. 我的猜测是它在文本段中(在非易失性存储器中),并从那里读取到堆栈。

Thank you for the answers. 谢谢你的回答。

The compiler gets to decide. 编译器可以决定。

The value may not even be "stored" anywhere: for some constants (eg zero) it's easier to just emit code to compute the value on demand rather than copy it from anywhere. 该值甚至可能不会“存储”在任何地方:对于某些常量(例如零),仅发出代码以按需计算该值而不是从任何地方复制它就容易了。

It's up to the compiler, of course, but whatever it is, it's going to be more or less the same as if you'd assigned a value to the variable within the expression. 当然,这取决于编译器,但是无论它是什么,它都将与为表达式中的变量分配值差不多相同。 That is, if you say 也就是说,如果你说

void foo()
{
    uint8_t x = 2u;
}

it's just as if you'd said 就像你说的那样

void foo()
{
    uint8_t x;    /* uninitialized */
    x = 2u;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM