1

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.

Runsva
  • 365
  • 1
  • 7
  • maybe split TEST() into 2 functions, one which returns a string and one which returns a boolean. or you could use pointers. i still do not understand why you want to this instead of just printing "res: 1\nstr: TEST" in loop. I'll write an answer that uses pointers. – ocean moist Jun 11 '23 at 00:22

2 Answers2

3

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

You can try passing the String variable by reference to the Test function as follows:

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

This should change the value of str variable inside the loop function.