Passing string types to a function

Discussion in 'C++' started by Suddn, Nov 12, 2003.

  1. Suddn

    Suddn Guest

    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.


    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.)

    Suddn, Nov 12, 2003
    1. Advertisements

  2. Suddn

    Derek Baker Guest

    void foo(string& s, string& s2)

    Derek Baker, Nov 12, 2003
    1. Advertisements

  3. 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.
    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)
    Andrey Tarasevich, Nov 12, 2003
  4. Suddn

    Jon Bell Guest

    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)
    Jon Bell, Nov 12, 2003
  5. Suddn

    jeffc Guest

    void foo(string& s, string& s2)
    jeffc, Nov 12, 2003
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.