easy program... but x_1 and x_2 strings dont change after return from function
I expect 50 and 70 but still keeps declaration value.

#include <cstdlib>
#include <iostream>

using namespace std;

void absurd (string a, string b)
{
    a="50";
    b="70";
}

int main(int argc, char *argv[])
{
    string x_1="burcin";
    string  x_2="erek";
    absurd(x_1,x_2);
    cout <<"\n"<<x_1<<" "<<x_2<<"\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}

Recommended Answers

All 4 Replies

By default, an std::string is passed to a function by value. When you pass an argument to a function by value, a copy of the argument is made and stored in the parameter. Because it's a copy, any changes you make to it within the scope of the function are not reflected in its original scope.

To accomplish what you want, you must pass them by reference. When you pass by reference, you are passing access, not a copy. Because you are passing access, changes within the function's scope are reflected in the original scope.

More info.

pass by reference

void absurd (string &a, string &b)
{
    a="50";
    b="70";
}
commented: Are you unaware that what you posted has already been mentions 15 hours earlier? Ego posting us rude. -3

thank you if i use pointer. it works.

thank you if i use pointer. it works.

Pointers are another slightly more complex, and more powerful, way of accomplishing a pass by reference. Well done.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.