Back to C++
2026-04-107 min read

Passing String to a Function (C++)

Learn Passing String to a Function (C++) step by step with clear examples and exercises.

Why This Matters

Understanding how to pass strings to functions in C++ is crucial for writing efficient, error-free, and flexible code. Since there's no built-in string data type in C++, we use character arrays to store sequences of characters. Passing these character arrays to functions requires knowledge of function parameters, arguments, passing by value, and passing by reference.

Prerequisites

Before diving into passing strings to functions, it's essential to have a good understanding of the following concepts:

  1. Variables and Data Types
  2. Arrays
  3. Pointers
  4. Functions in C++
  5. Input/Output (I/O) Streams
  6. Basic Operators (e.g., arithmetic operators, comparison operators, assignment operator)
  7. Control Structures (e.g., if-else statements, loops)
  8. Standard Template Library (STL) basics (e.g., vectors, iterators)
  9. Dynamic Memory Allocation (e.g., new and delete)
  10. Structure of a C++ Compiler (e.g., Preprocessing, Compilation, Linking)

Core Concept

In C++, we use character arrays to represent strings. To pass these character arrays to functions, we need to understand how function parameters and arguments work.

Passing Strings by Value

Passing strings by value means that a copy of the original string is created and sent to the function. This method is inefficient for large strings due to unnecessary memory usage but allows the called function to modify the string without affecting the original one.

void printString(char str[]) {
std::cout << "The given string: " << str;
}

int main() {
char myString[] = "Hello, World!";
printString(myString);
return 0;
}

In this example, the printString function takes a character array as an argument and prints its content. The original string "Hello, World!" is passed by value to the function, which creates a new copy of it.

Passing Strings by Reference

Passing strings by reference means that we pass a reference (address) of the original string to the function instead of creating a copy. This method is more efficient for large strings and allows the called function to modify the original string.

void printString(char str[]) {
std::cout << "The given string: ";
std::cout << str; // No need for << operator since str is a character array
}

int main() {
char myString[] = "Hello, World!";
printString(&myString[0]); // Passing the address of the first element in the array
return 0;
}

In this example, the printString function takes a character array as a reference parameter. This allows the function to directly access and manipulate the original string without creating a copy.

Passing Strings by Constant Reference

Passing strings by constant reference is similar to passing by value but with a const qualifier. It ensures that the called function cannot modify the original string.

void printString(const char str[]) {
std::cout << "The given string: " << str;
}

int main() {
char myString[] = "Hello, World!";
printString(myString); // Passing the original string by constant reference
return 0;
}

In this example, the printString function takes a character array as a constant reference parameter. This ensures that the function cannot modify the original string.

Worked Example

Let's create a simple function that reverses a given string using passing by value and passing by reference:

#include <iostream>
#include <string> // For std::reverse()

void reverseStringByValue(char str[]) {
int length = std::strlen(str);

for (int i = 0; i < length / 2; ++i) {
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}

void reverseStringByReference(char* str) {
int length = std::strlen(str);

std::reverse(str, str + length); // Using STL's std::reverse() function
}

int main() {
char myString[] = "Hello, World!";

std::cout << "Original String: " << myString << "\n";

reverseStringByValue(myString);
std::cout << "Reversed String (by value): " << myString << "\n";

reverseStringByReference(&myString[0]);
std::cout << "Reversed String (by reference): " << myString << "\n";

return 0;
}

In this example, we define two functions: reverseStringByValue and reverseStringByReference. Both functions take a character array as an argument but use different methods to reverse the string. The first function reverses the string using manual iteration, while the second function uses the Standard Template Library (STL) function std::reverse().

Common Mistakes

  1. Forgetting to include necessary headers: Make sure you include the correct header files for I/O streams and other functions used in your code.
  2. Not understanding the difference between passing by value, passing by reference, and passing by constant reference: Passing strings by value can lead to unnecessary memory usage, while passing by reference allows the called function to modify the original string. Passing by constant reference ensures that the function cannot modify the original string.
  3. Incorrectly using string manipulation functions: Be careful when using string manipulation functions like std::strlen(), std::reverse(), or others. Make sure you understand their arguments and return types.
  4. Not defining the size of character arrays: When defining character arrays, always ensure that they are large enough to hold the intended strings to avoid segmentation faults.
  5. Not handling string termination: Remember that character arrays used for strings should be null-terminated (i.e., the last element should be '\0').
  6. Not checking for string length: Ensure that your functions handle strings of varying lengths, and don't assume a fixed size for the input string.
  7. Forgetting to pass the address of character arrays: When passing character arrays as function arguments, always pass the address of the first element in the array (e.g., &myString[0]).
  8. Not using const qualifiers properly: Use const qualifiers when appropriate to ensure that functions cannot modify original strings.

Practice Questions

  1. Write a function that concatenates two given strings using passing by value.
  2. Write a function that checks if a given string is a palindrome using passing by reference.
  3. Write a function that finds the length of a given string using passing by value and another function that uses passing by reference. Compare their performance on large strings.
  4. Write a function that reverses a given string using passing by value, but ensure it doesn't modify the original string. Hint: Create a new character array to store the reversed string.
  5. Write a function that takes a character array and a specific character as arguments, and returns the number of occurrences of the character in the string.
  6. Write a function that sorts an array of strings using passing by value and quicksort algorithm.
  7. Implement a simple text editor that allows users to input strings, save them in a file, and load them back into memory for editing. Use passing by reference to modify the user's input in the main function.
  8. Write a function that counts the number of words in a given string using passing by value and another function that uses passing by reference. Compare their performance on large strings.
  9. Implement a simple calculator that takes two operands as character arrays and performs arithmetic operations like addition, subtraction, multiplication, and division. Use passing by value for the operands and passing by reference for the result.
  10. Write a function that finds the longest common subsequence of two given strings using dynamic programming and passing by reference to store intermediate results.

FAQ

  1. Why can't we use std::string instead of character arrays?
  • Using std::string is more efficient and easier for handling strings, but it may not be suitable for certain situations where low-level manipulation or compatibility with legacy code is required.
  1. What happens when a string exceeds the size of its character array?
  • If a string exceeds the size of its character array, it will result in a segmentation fault (accessing memory outside the allocated space). To avoid this, always ensure that your character arrays are large enough to hold the intended strings.
  1. Can we pass strings as function arguments without using character arrays?
  • Yes, C++11 introduced std::string as a built-in data type, which can be used as a parameter for functions. However, this is not covered in this lesson as it requires knowledge of std::string and its associated functions.
  1. What is the difference between char* and char[]?
  • Both char* (pointer to char) and char[] (array of chars) can be used to represent strings in C++, but they have slightly different syntaxes and usage patterns. char[] is an array with an implicit size determined by the number of elements provided, while char* requires explicit memory allocation using operators like new.
  1. Why do we pass character arrays as pointers instead of arrays in C++?
  • In C++, when a function takes an array as an argument, it receives a pointer to the first element of the array (i.e., &array[0]). This is why we often see character arrays passed as pointers in C++ code.
  1. What is stringization in C++?
  • Stringization in C++ is the process of converting a constant expression into a string literal using the preprocessor function #. For example, #define MY_STRING "Hello, World!" creates a macro that expands to the string literal when used in code. This can be useful for creating compile-time constants or debugging messages.
Passing String to a Function (C++) | C++ | XQA Learn