Search code examples
c++arduinoarguments

Assign Value to String Function Argument? (Arduino)


I'm attempting to understand what the proper way to assign a value to a String function argument in Arduino.

Let's say I have the following testing code:

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  String str;
  bool res = TEST(str);
  Serial.println("res: " + String(res));
  Serial.println("str: " + str);

  delay(1000);
}

bool TEST(String str)
{
  str = "TEST";
  return true;
}

In the code above, I want the str local variable defined inside the loop function to attain a value of "TEST" upon every call to the TEST function. However, I want the TEST function to return a boolean, which is assigned to the local variable res, and for my String variable str to be assigned it's value of "TEST" inside the TEST function by modifying the argument.

The code above currently outputs the following to the Serial Monitor:

res: 1
str: 

And I would like for the output to be the following:

res: 1
str: TEST

I guess I'm misunderstanding how value assignments to function arguments work. Is that only possible if the function argument is a pointer?

Thanks for reading my post, any guidance is appreciated.


Solution

  • By default a parameter to a function is copied by value. Any changes you make to it are local to the function and stay within the function.

    To change this you can pass by reference:

    bool TEST(String &str)
    //               ^
    {
      str = "TEST";
      return true;
    }
    

    Yes you could use a pointer, but that's old-fashioned C style coding.