-2

why does the below function (f) work when i put cout in the function body but does't work when i put cout after the function call

#include <iostream>
using namespace std;
void f(string str)
{
    int size=str.size();
    for (int i=0;i<size/2;i++)
    {
        char temp=str[i];
        str[i]=str[size-i-1];
        str[size-i-1]=temp;
    }
}
int main ()
{
    string a="abcd";
    f(a);
    cout<<a;   //output: abcd 
}
#include <iostream>
using namespace std;
void f(string str)
{
    int size=str.size();
    for (int i=0;i<size/2;i++)
    {
        char temp=str[i];
        str[i]=str[size-i-1];
        str[size-i-1]=temp;
    }
    cout<<str;
}
int main ()
{
    string a="abcd";
    f(a);  //output: dcba
}

I am new to programming so i don't know concepts like pointers which i am guessing is the problem here.

  • 2
    Hint: You're copying the string as an argument, then modifying a **local copy**. Consider `return str`. – tadman Dec 30 '22 at 15:41
  • 3
    *I am new to programming* - [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Evg Dec 30 '22 at 16:11
  • 1
    Put the output statement from the first example back into the second example (i.e., in `main` **after** the call to `f`. You'll see that nothing has changed. When you're analyzing something you don't understand (which we all end up doing much of the time), only change one thing at a time. So add the output statement to `f`, but don't remove the output statement from `main`. – Pete Becker Dec 30 '22 at 16:56

1 Answers1

4

This is because the variable a is not modified by the function void f(string str). f takes a copy of the string and then uses that copy to reverse the string. This means that the original string a is unchanged.

If you want to make it so that f does not take a copy, you can pass the string by reference using the & operator.

void f(string& str) will use the same string for a and str as they will be referring to the same data in memory.

Cedric Martens
  • 1,139
  • 10
  • 23