Yes. In Arduino C++, pass a String to a function by putting its type in the parameter list, such as void showMessage(const String& message), then call it with a String variable. You can also pass text as a C-style string using const char*; the best choice depends on whether the function needs to modify the text and how you want to manage memory.
What a function parameter does
A function parameter is a named input that receives a value when the function is called. The parameter declaration specifies the kind of value the function accepts. For an Arduino String object, the basic form is void functionName(String text). The call might look like functionName(message), where message is a previously declared String.
For example, this function prints the text it receives:
void showMessage(String message) {
Serial.println(message);
}
Call it from setup() or another function after serial communication has been started:
String message = "Ready";
showMessage(message);
The function can use the parameter name message inside its braces. That name is local to the function, so it does not have to match the variable name used at the call site. For example, showMessage(statusText) still supplies the value to the parameter named message.
Passing a String by value
In the first example, String message passes the object by value. The function receives its own parameter object, initialized from the argument. If the function changes that parameter, the caller’s original variable is not changed:
void addMark(String text) {
text += "!";
}
String greeting = "Hello";
addMark(greeting);
Serial.println(greeting); // Prints Hello
Passing by value can be straightforward, particularly when the function should work with a separate copy. It can also require copying the String’s contents and allocating memory, depending on the core’s implementation and the operation. On a small microcontroller, unnecessary copies may use scarce RAM or add overhead, especially if the function is called frequently or the text is long.
Do not assume that a by-value parameter is a reference to the caller’s object. If the function should change the caller’s String, choose a reference parameter instead. If it only needs to read the text, a constant reference is usually a better default for a String object.
Use const String& when the function only reads
A parameter written const String& message is a reference to the caller’s String, with const preventing the function from changing it through that parameter. The ampersand means reference in this declaration; it does not mean that the function receives a separate copy of the String contents.
void showMessage(const String& message) {
Serial.println(message);
}
String statusText = "Sensor ready";
showMessage(statusText);
This is a useful general pattern for functions that inspect, compare, print, or otherwise read a String without modifying it. It avoids the ordinary by-value parameter copy and documents the function’s intent. The function can still call read-only operations on the object, but an attempt to change it through message will be rejected by the compiler.
A const reference can also bind to a temporary String created for a function call, so a call such as showMessage("Ready") works with the Arduino String class on common Arduino cores. The temporary remains alive for the duration of the call. If portability across different C++ environments matters, or overload resolution becomes confusing, declare a String variable explicitly or provide a separate const char* overload.
Use String& when the function must modify the caller’s text
To edit the original String, declare a non-const reference parameter: String& text. Changes made through that reference affect the object supplied by the caller:
void addExclamation(String& text) {
text += "!";
}
String greeting = "Hello";
addExclamation(greeting);
Serial.println(greeting); // Prints Hello!
This is different from passing by value: no separate parameter object is intended, and the caller sees the modification. A reference parameter also requires an appropriate existing String object; it cannot bind to a temporary in the same way a const reference can. Use it only when changing the caller’s value is part of the function’s purpose. A function that unexpectedly alters its input can make sketches harder to understand, so make that behavior clear in the name or documentation.
If a function needs to produce text rather than alter an input, another option is to return a String. For a short result, a return value can make the data flow clear, but constructing and returning strings may involve allocation or copying depending on compiler optimization and the core. For larger or frequently generated text, consider whether a caller-provided buffer is more suitable.
Passing a C-style string or character array
Arduino sketches also commonly use C-style strings: character data terminated by a null character, written '\0'. A function that only reads this data can accept const char*:
void printLabel(const char* label) {
Serial.println(label);
}
printLabel("Temperature");
A string literal such as "Temperature" is suitable for this read-only parameter. A character array can also be supplied:
char label[] = "Temperature";
printLabel(label);
In a function parameter, an array parameter is adjusted to a pointer parameter, so a declaration such as void printLabel(const char label[]) is effectively treated as a pointer parameter. The function does not automatically receive the array’s length. If it must know the available capacity, pass the length separately or use a type that carries that information.
Use const char* for read-only character data. A writable char* does not make a string literal safe to edit; modifying a literal has undefined behavior in C++. If a function needs to change a character buffer, pass a writable array with enough space, and make the buffer capacity explicit so the function cannot write past its end.
Converting between String and const char*
A String object and a C-style string are related but are not interchangeable types. When a library function expects const char*, an Arduino String provides c_str() to obtain a pointer to its character data:
void printLabel(const char* label) {
Serial.println(label);
}
String label = "Temperature";
printLabel(label.c_str());
The pointer returned by c_str() refers to storage managed by the String object. Do not keep that pointer for use after the String is destroyed, and avoid relying on it after changing the String; a change may reallocate its storage. For a call that uses the pointer immediately, as above, the String remains alive throughout the call.
Conversely, a C string can be used to create a String object: String text = "Ready";. This conversion is convenient, but it creates or uses a String object and its memory management. If a function is called repeatedly with fixed text, accepting const char* can avoid constructing a new String for every call. If the function needs String-specific operations, accepting a String reference may be clearer.
Memory considerations on Arduino boards
Arduino boards vary considerably in processor, available RAM, and core implementation. An Uno-class AVR board has much less RAM than many modern 32-bit boards, so dynamic text deserves more attention on smaller devices. Arduino String manages character storage dynamically. Repeated growth, concatenation, and temporary objects can lead to allocation overhead; on constrained systems, patterns of repeated allocation and release may also contribute to heap fragmentation.
This does not mean that String is always unsafe or should never be used. It is convenient and can be appropriate when messages are short, memory use is controlled, and the target has enough RAM. To make use more predictable, consider these habits:
- Prefer
const String&for a function that only reads an existing String, rather than needlessly taking it by value. - For a String that will grow, call
reserve()when you can estimate its required capacity, reducing the need for repeated reallocations. - Avoid building long messages through many small concatenations in a frequently repeated loop on a memory-limited board.
- For fixed messages, consider string literals and functions that accept
const char*. - Measure free memory and test on the actual board when a sketch has tight RAM limits; behavior on a desktop does not establish that an embedded sketch has enough memory.
Using a C-style string is not automatically safer: buffers need adequate capacity and correct null termination. Choose based on the program’s memory constraints and the interface expected by the libraries you use.
Choosing the right parameter type
Before writing the function signature, decide what the function should do with the text. This quick guide covers the usual cases:
const String&: read or inspect an existing Arduino String without making an ordinary by-value parameter copy.String&: intentionally change an existing String supplied by the caller.String: work with a separate parameter object, accepting the possibility of a copy and its memory cost.const char*: read null-terminated character data, including literals, without requiring the caller to supply a String object.char*or a character array plus capacity: edit a writable buffer, provided its lifetime and available space are managed correctly.
For example, a function that prints a label could accept const char* if it needs only character data, or const String& if the surrounding code already uses Arduino String and the function benefits from that type. A function that appends a suffix to a user’s String should use String& and make the change explicit. The parameter type is part of the function’s interface, so matching it to the intended behavior makes calls easier to reason about.
Common mistakes and troubleshooting
A frequent mistake is leaving out the parameter type or using the wrong capitalization. Arduino’s class is spelled String, with a capital S; lowercase string is not the same type. A declaration such as void showMessage(message) is not a valid C++ function parameter declaration because the parameter’s type is missing.
Another common issue is expecting a by-value function to update the original variable. Change the parameter to String& if that is intended, or return the new text. Conversely, if a function should not modify its input, use const String& so accidental changes are caught during compilation.
If a function is called before the compiler has seen its declaration, it may report that the function was not declared in this scope. In an Arduino .ino sketch, the Arduino build system commonly generates function prototypes, but this convenience does not apply identically to every source-file arrangement. In a separate .cpp file or ordinary C++ project, declare the function in a header or place a declaration before the call. Also ensure the declaration and definition use matching parameter types; String, String&, and const String& are distinct signatures.
Finally, check the lifetime of any pointer passed from c_str(), and do not treat a character array as if its length travels with it. These issues are separate from the function-call syntax, but they are common causes of bugs when text crosses a function boundary.
Frequently Asked Questions
Can an Arduino function take a String parameter?
Yes. Declare a parameter such as String text, const String& text, or String& text, depending on whether the function should receive a separate object, read the input, or modify the caller’s object.
Should I pass Arduino String by value or by reference?
For a function that only reads a String, const String& is a common choice because it avoids an ordinary by-value parameter copy and prevents modification through the parameter. Use by value when a separate parameter object is useful and its possible memory cost is acceptable.
How do I change a String inside a function?
Pass it by non-const reference, for example void edit(String& text), then modify text inside the function. The caller’s String will reflect those changes. A by-value parameter changes only the function’s local parameter object.
Can I pass a string literal to an Arduino function?
Yes. A function with a const char* parameter can receive a literal directly. A function taking const String& can also commonly receive a literal through temporary String construction, though an explicit variable or C-string overload can make the intended conversion clearer.
How do I pass an Arduino String to a function expecting const char*?
Call the function with myString.c_str(). The returned pointer is owned by the String, so use it while that String remains alive and avoid keeping it across changes that could reallocate the text.
Related
- String Length in C++: size(), length(), and Examples
- Reverse a String in C++: std::reverse and Examples
- JavaScript split() Method: Syntax, Examples, and Tips
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Using OFFSET in Excel: Syntax, Examples, AlternativesIn Microsoft Excel for Microsoft 365, OFFSET returns a reference to a cell or range at a specified…
- MIN Function for Dates in Excel: Find the Earliest DateTo find the earliest date in an Excel range, use the MIN function: if your dates are in…
- Excel COUNTIF Range Contains Text: Formula GuideYes, you can use COUNTIF to count cells that contain text, but the exact formula depends on what…
- Excel Power Query vs Formulas: Which Should You Use?Use Excel formulas when you want calculations to update as you edit worksheet cells; use Power Query when…
- Edit a Custom Sort List in ExcelTo edit a custom sort list in Excel for Microsoft 365 on Windows, open File > Options >…
- How to Subtract in Excel Using the SUM FunctionTo subtract with Excel’s SUM function, add the amount you are starting with and include each amount to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.