why do i get the same value of the address?

后端 未结 4 1751
无人共我
无人共我 2020-12-11 07:13
#include
#include

void vaibhav()
{
    int a;
    printf(\"%u\\n\",&a);
}

int main()
{
    vaibhav();
    vaibhav();
    vaibhav(         


        
4条回答
  •  猫巷女王i
    2020-12-11 07:43

    "a" in the function vaibhav() is an automatic variable, which means it's auto-created in the stack once this fun is called, and auto-released(invalid to the process) once the fun is returned. When funA(here is main) calls another funB(here is vaibhav), a stack frame of funB will be allocated for funB. When funB returns, stack frame for funB is released.

    In this case, the stack for funB(vaibhav) is called 3 times sequentially, exactly one by one. In each call, the stack frame for funB is allocated and released. Then re-allocated and recycled for times.

    The same memory block in stack memory is re-used for 3 times. In that block, the exact memory for "a" is also re-used for 3 times. Thus, the same memory and you get the same address of it.

    This is definitely compiler dependent. It depends on the compiler implementation. But I believe almost every C compiler will produce the same result, though I bet there is no specific requirement in C standard to define the expected output for this case.

提交回复
热议问题