Passing string types to a function

S

Suddn

Help me get my mind around passing string types to a function.

I need to have the function modify the string types and get them back.
Normaly I would just return the modified string but I need to modify about
five different strings.

I thought that strings were passed by reference in C/C++ but when I pass
the strings in they remain unaltered in the calling function. I did test
the function being called and they are being althered there.

Can someone please show me the syntax that I need.

i.e.

void foo(string s, string s2)
{

}

int main(int argc, char *argv[])
{
string a, b;
foo(a, b);
return 0
}

Or whatever is correct (the above doesn't work.)

Thanks.
 
A

Andrey Tarasevich

Suddn said:
...
I thought that strings were passed by reference in C/C++ but when I pass
the strings in they remain unaltered in the calling function. I did test
the function being called and they are being althered there.
...

The compiler will pass the strings the way you asked it to pass them. If
you direct the compiler to pass them by value, it will pass them by
value. The same applies to passing by reference.
void foo(string s, string s2)

This function will receive its arguments by value. In order to receive
them by reference you have to declare it as follows

void foo(string& s, string& s2)
 
J

Jon Bell

I thought that strings were passed by reference in C/C++

That refers to C-style strings which are just arrays of char. Arrays in
general are passed implicitly by reference.

C++ style strings behave like "normal" data types as far as passing them
to functions is returned. If you want to change the value inside the
function and have that change communicated back to the calling function,
pass it by reference, or by pointer. The same applies for vectors, by the
way, if you're using them instead of arrays (which you probably should).
void foo(string s, string s2)
{

}

void foo (string& s string& s2)
 
J

jeffc

Suddn said:
I thought that strings were passed by reference in C/C++ but when I pass
the strings in they remain unaltered in the calling function. I did test
the function being called and they are being althered there.

Can someone please show me the syntax that I need.

i.e.

void foo(string s, string s2)
{

}

int main(int argc, char *argv[])
{
string a, b;
foo(a, b);
return 0
}

void foo(string& s, string& s2)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top