0

I came across this question and I would like to know why the address of a non constant string created on the stack of a method returns a constant pointer when its address is requested. I have copy-pasted the code sample used there

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}

int main()
{
    // ...
    string s;
    myfunc(&s);
    // ...
} 

My question is that & returns the address of a variable. So In the above case the std::string s is a non constant then why is it returning its address as a constant ? What I want to know is why the address of the non-constant string is returned as a constant address. Are the addresses of all objects created on the stack constant ?

Community
  • 1
  • 1
Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

1 Answers1

1

Let's say you did:

void myfunc(string*& val)
{
    val = NULL;
    // How is that supposed to affect the variable s in main?
    // You can't change the address of the object in main.
    // Once a variable is created, its address cannot be modified.
}

int main()
{
    // ...
    string s;

    // Since the address of s cannot be changed,
    // the type of &s is "string* const" not "string&".

    // That's why the call to myfunc is wrong.
    myfunc(&s);
} 
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Thanks for clearing this up. So you are saying that an object when created on the stack actually has a constant address. – Rajeshwar May 26 '15 at 17:24
  • 2
    @Rajeshwar, addresses of objects, whether they are on the stack or they are global are constant. – R Sahu May 26 '15 at 17:25
  • `&s` is prvalue of type `string *` and reference to lvalue of type `string *` (parameter type of your function) cannot be bound to it – robal May 26 '15 at 17:35