Passing a string to a function in C++ is a fundamental skill. You can pass a std::string by value (copy), by reference (no copy, modifiable), by const reference (no copy, read-only), or as a C-style const char*. The most common and efficient way for modern C++ is to pass by const std::string& when you only need to read the string, and by std::string& when you need to modify the original. This guide walks you through each method, with code examples and practical tips.
What You’ll Need
- A C++ compiler (e.g., GCC, Clang, MSVC) and a text editor or IDE.
- Basic understanding of functions and the
std::stringclass. - Include the
<string>header in your source file.
Step-by-Step
- Include the string header. At the top of your .cpp file, add
#include <string>to use thestd::stringtype. - Decide how you want to pass the string.
- By value – the function gets a copy. Use when you need to modify the string locally without affecting the caller.
- By reference – the function works directly on the original string. Use when you need to modify the caller’s string.
- By const reference – the function reads the original without copying and cannot modify it. Use this for read-only access to avoid overhead.
- As
const char*– for compatibility with C-style APIs or when you have a string literal.
- Write a function that takes a string by value.
void printByValue(std::string s) { std::cout << s << std::endl; }Call it with a string variable or literal:
printByValue("Hello");orprintByValue(myString);. The parametersis a copy; changes inside the function do not affect the original. - Write a function that takes a string by reference.
void addExclamation(std::string &s) { s += "!"; }This modifies the original string. Call it like
addExclamation(myString);– after the call,myStringwill have an exclamation mark appended. - Write a function that takes a const reference.
size_t getLength(const std::string &s) { return s.length(); }This is the recommended way for read-only access. It avoids copying and prevents accidental modification. Call it with any string:
getLength(myString)orgetLength("temp"). - Write a function that takes a C-style string.
void printCString(const char *str) { std::cout << str << std::endl; }Call it with a string literal:
printCString("Hello");or withmyString.c_str()to convert astd::stringto aconst char*. - Test your functions. Write a simple
mainthat creates a string, passes it to each function, and observes the behavior. For example:int main() { std::string greeting = "Hello"; printByValue(greeting); addExclamation(greeting); std::cout << greeting << std::endl; // prints "Hello!" std::cout << getLength(greeting) << std::endl; // prints 6 printCString(greeting.c_str()); return 0; } - Compile and run. Use your compiler, e.g.,
g++ -std=c++11 -o test test.cppand then run./test(on Windows:test.exe).
Common Mistakes
- Forgetting to include
<string>– causes compile errors about unknown typestd::string. - Using
std::stringwithout thestd::prefix – unless you haveusing namespace std;, which is generally discouraged in larger projects. - Passing a string literal to a non-const reference – you cannot bind a temporary to a non-const lvalue reference. For example,
addExclamation("Hello");will not compile because"Hello"is a temporary. Use a variable or a const reference instead. - Modifying a const reference parameter – attempting to change a
const std::string&will cause a compile error. If you need to modify, use a non-const reference. - Using
c_str()and storing the pointer – the pointer returned byc_str()is only valid until the string is modified or destroyed. Do not store it for later use. - Passing by value for large strings unnecessarily – copying a large string is expensive. Use const reference for read-only access.
Tips
- Prefer
const std::string&for read-only parameters. It avoids copying and clearly signals that the function will not modify the input. - Use
std::string_view(C++17) for read-only parameters that may accept string literals orstd::stringwithout copying. It is more flexible and avoids creating astd::stringtemporary when passing a literal. However, be careful: astring_viewdoes not own the data, so it must remain valid during the function call. - If you need to modify the string and also want to avoid copying, pass by reference. This is efficient and changes the original.
- For C-style APIs, use
c_str()to get aconst char*. Remember that the pointer is valid only until the string is modified. - Mark functions that do not modify parameters as
constif they are member functions. This is a separate concept but helps with const-correctness.
Troubleshooting
- Compile error: ‘string’ is not a member of ‘std’ – Make sure you have
#include <string>at the top of your file. - Compile error: cannot bind non-const lvalue reference to an rvalue – You are trying to pass a temporary (like a string literal) to a function expecting a non-const reference. Change the parameter to
const std::string&or create a variable first. - Function does not modify the original string when you expected it to – You likely passed by value. Check the function signature: if it is
std::string s, it’s a copy. Change tostd::string&. - Program crashes when using
c_str()later – The string was modified or destroyed after you obtained the pointer. Do not store the pointer; use it immediately or copy the data. - Performance is slow when passing many large strings – You are probably passing by value. Switch to const reference or
std::string_view(if C++17).
Frequently Asked Questions
- What is the difference between passing by value and by reference? By value creates a copy; changes inside the function do not affect the original. By reference passes the original object; changes affect the caller’s variable.
- When should I use
const std::string&instead ofstd::string? Use const reference when you only need to read the string and want to avoid the cost of copying. This is the most common case for functions that just inspect or process the string. - Can I pass a string literal to a function expecting
std::stringby value? Yes, the literal is implicitly converted to a temporarystd::stringand then copied into the parameter. This works but may be slightly less efficient than passing aconst char*orstd::string_view. - How do I pass a string to a function that needs to modify it? Pass by non-const reference:
void modify(std::string &s). Then changes inside the function affect the original. - What is
std::string_viewand should I use it?std::string_viewis a lightweight, non-owning view of a string. It is useful for read-only parameters that can accept bothstd::stringand string literals without copying. It requires C++17 or later. - Why can’t I pass a string literal to a non-const reference? Because a string literal is a temporary object (an rvalue). Non-const lvalue references cannot bind to rvalues. You can either use a const reference, pass by value, or create a named variable.
Related
- Maximum Data Entry: Definition, Limits, and Real Usage
- Number Shortcut Keys: Full List & How to Use Them
- String in Java: Top Interview Questions Answered
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Align Text Shortcut: Left, Center, Right & MoreIn Excel for Microsoft 365 on Windows, select the cell or range and press Alt, H, A, L…
- Show Formulas in Excel: Keyboard Shortcut GuideTo show formulas in Excel for Microsoft 365 on Windows, press Ctrl+` (Ctrl plus the grave accent key,…
- Excel SUM Without Hidden Cells: Which Formula to UseTo sum only visible rows in Excel, use SUBTOTAL with function number 109. With amounts in B2:B6 and…
- Remove Duplicates in Excel: Sort Data the Right WayTo remove duplicates in Excel and keep the right record, sort your data first if the order determines…
- Excel LET Function: How to Name and Reuse CalculationsUse Excel’s LET function to give a name to a value or calculation, then use that name elsewhere…
- Excel COUNTIF Wrong Result? Fixes & CausesIf your Excel COUNTIF is returning a wrong result, the most common causes are mismatched data types (text…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.