user1649972 user1649972 - 1 month ago 9
C++ Question

Return a string / pass by reference

I am writing some C++ code for an Arduino board which has some hardware attached. In various places in the code I need to construct a string with values of the various attached hardware and send it over serial as part of a command. As it needs to be part of a very specific command sent over serial I construct it first and send it when the entire command is ready.

At the moment I am doing it via the function below

'String constructDataString ()
{
// Set up data to transmit
String dataStr = String(var1);
dataStr += ",";
dataStr += String(var2);
dataStr += ",";
dataStr += String(var3);
dataStr += ",";
dataStr += String(var4);
dataStr += ",";
dataStr += String(var5);

return dataStr;
}'


I then call it with

String dataString = constructDataString ();


I was wondering if it was possible to do this by declaring a string in main and then passing it to the function by reference and allowing the function to modify it directly. I have tried this a few ways but I am having trouble getting it to work. I tried something like below but not that familiar with doing this so I was hoping someone might be able to help.

Prototype

void constructDataString (String* extString)


Call from main

String dataString =””;
String* dataStringPtr = & dataString;
constructDataString (dataStringPtr);


Function

void constructDataString (String* extString)
{
// Set up data to transmit
extString = String(var1);
extString += ",";
extString += String(var2);
extString += ",";
extString += String(var3);
extString += ",";
extString += String(var4);
extString += ",";
extString += String(var5);
}

Answer

Sure, you can. However in the body of constructDataString, you need to use *extString instead of extString to dereference the pointer. Otherwise, you can use a reference in C++.

With the reference, the code would be:

void constructDataString (String& extString)
{
 // Set up data to transmit
    extString = String(var1);                           
    extString += ",";
    extString += String(var2);                                  
    extString += ",";
    extString += String(var3);      
    extString += ",";
    extString += String(var4);  
    extString += ",";
    extString += String(var5);
}

and you use it as follows:

String dataString =””;
constructDataString (dataString);