简体   繁体   中英

Does local non-static variable get same memory address each time function/method is called?

I have made a fun called show() in it i have declared a static and a non -static variable; I am observing one thing that each time my non-static local variables are getting same memory address when i am calling it.

i just want to know that this happens always or it is just a coincident;

#include<iostream>
#include<cstring>
using namespace std;
void show()
{
  static int x = 10;  
   int y = 20; 
 
  cout<<"Address of y = "<< &y<< endl; 
  cout<< "x = "<< x<< " , y = "<< y<< endl;

  x++;
  y++;
}

int main()
{
  show();

  int x = 10; 
  cout<< x<< endl; 
  cout<< "len = "<< strlen("Kumar")<< endl; 

   show();
  show();
  return 0;
}

Out put of the program 
Address of y = 0xd01f5ffc6c
x = 10 , y = 20
10
len = 5
Address of y = 0xd01f5ffc6c
x = 10 , y = 20
Address of y = 0xd01f5ffc6c
x = 10 , y = 20

It's related entirely to your call stack.

I added this method to your code:

void foo() {
    cout << "\nCalled from Foo.\n";
    show();
}

I then called foo() from main() . My output:

-$ g++ Foo.cpp -o Foo && Foo
Address of y = 0x7ffc709566d4
x = 10 , y = 20
10
len = 5
Address of y = 0x7ffc709566d4
x = 11 , y = 20
Address of y = 0x7ffc709566d4
x = 12 , y = 20

Called from Foo.
Address of y = 0x7ffc709566c4
x = 13 , y = 20

As you can see, it moved.

You should take the time to learn about stacks and the stack pointer, and how C and C++ store local variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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