StudentX
StudentX

Reputation: 2323

std::string defined in a function retains its previous value?

If a string is defined in a function, does it retain its value between calls ?

Something like this :

std::string myFunction( std::string input)
{
    std::string output;

    for ( int i=0; i < input.length(); i++ )
    {
        output[i] = input[i];
    }

    return output;

}

If the input string's length is longer in the first call to the function than the length of the input in the second call, then the string returned in the second call still has last few(same as the difference in length) characters of the previous call intact.

Upvotes: 0

Views: 135

Answers (2)

Israel Unterman
Israel Unterman

Reputation: 13510

It doesn't. I believe you ask this about a string and not about every other local variable, since a string uses the heap. That's right, but string also has a destructor, which is called upon exiting from scope, deallocating the heap it used.

Of course, you might find that it did retain its value, but that would be just a coincidence of allocating the same memory area again (which might happen again and again, depending on your program, memory environment, compiler, etc..).

Upvotes: 1

NPE
NPE

Reputation: 500585

If a string is defined in a function, does it retain its value between calls ?

In well-defined code it doesn't, unless it's declared static.

The main problem with your current implementation is the body of the loop:

for ( int i=0; i < input.length(); i++ )
{
    output[i] = input[i];
}

Here, you're assigning past the end of output, which is undefined behaviour. Once you're in the realm of undefined behaviour, anything can happen.

Upvotes: 2

Related Questions