1

Suppose I want to write a C++ function foo() that updates the value of an input string. How do I do it? The code should probably look something like I have below but I don't know how to properly pass the string such that it is updated by the function.

void foo(String x) // Not sure if I should put an & or * before x
{
    x += " Goodbye";
}

void main()
{
    String x = "Hello World";
    cout << "x = " << x << endl;
    foo(x);  // Not sure if I should pass a pointer to x,
             // a reference to x or what?

    cout << "After foo (), x = " << x << endl;
}

(FYI, I'm writing this for an Arduino processor)

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

3 Answers3

4

Pass by reference:

void foo(String& x)
{
    x += " Goodbye";
}

The & means the parameter is a reference to the String outside the function rather than a copy.

Galik
  • 47,303
  • 4
  • 80
  • 117
1

In order to update the string from within the function, you need to pass a reference to the string as input:

void foo(String& x) 
{
    x += " Goodbye";
}

This SO post explains the difference between pass-by-reference and pass-by-value.

Regarding your confusion between using & or * in the function signature, you can either

  1. use & as described above OR
  2. you could define foo as void foo(String *x). However, in this case, when you call foo, you would need to call it as foo(&x);.

In the first case, you're passing the input as a reference variable while in the second case, you're passing it in as a pointer variable. The differences between them are explained in this post.

Community
  • 1
  • 1
jithinpt
  • 1,204
  • 2
  • 16
  • 33
1

You can use either of the following methods: -

  1. void foo(String *x) in function header and foo(&x); in main().

or,

  1. void foo(String &x) in function header and foo(x); in main().