0

I was just playing with the functions and parameters.

#include <iostream>
using namespace std;

int function(char *str,int b);
int main()
{
       char *str = new char[10];
       memset(str,0,10);

       int a = 10;
       int b = 10;
       function(str,b);
       function(str,a);
}

//FUnction Definition
 int function(char *str,int b)
 {
      cout << &str << "\t" << &b << "endl"

      return 0;
 }

I am compiling this code in VS2010 C++ ,, When we pass something by value , a new value is created copying the contents from the variable which is passed. So definitely b at the function body will be having different address. What i am seeing is that the function parameters remains at the same address location in multiple calls.

What i am guessing is that parameters of the Functions are each mapped with memory locations, which wil contain the variables called on Function

I just want to know is this so or there is something else.

rullof
  • 7,124
  • 6
  • 27
  • 36
ATul Singh
  • 490
  • 3
  • 15

2 Answers2

0

The addresses of local variables can be re-used for subsequent calls. Nothing wrong with this.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

The reason the local variables are at the same address in memory is because you are calling from main -> function and the stack is always being adjusted in the same way to make the locals for function

If you changed your code to that main called another function which then called function then you'd notice that the local variables and parameter have a different address as they'll be in a stack frame at a different address.

NOTE: All this is assuming your compiler isn't doing and optimizations.

Sean
  • 60,939
  • 11
  • 97
  • 136