Home > Article > Backend Development > What is the difference when a C++ function returns an array?
C functions have two behaviors when returning an array: a copy is returned by value, and changes to the copy do not affect the original array; a reference to the original array is returned by reference, and changes to the returned array are directly reflected in the original array.
In C, functions can return various types of data, including arrays. When a function returns an array, there are two different behaviors:
When returning an array by value, the function creates a copy of the array and returns it to the caller. This creates a new copy of the memory, and any changes made to that copy will not affect the original array.
Syntax:
int* foo() { int arr[] = {1, 2, 3}; return arr; }
Practical case:
int main() { int* arr = foo(); arr[0] = 10; // 更改副本值,不影响原始数组 return 0; }
Return an array by reference , the function directly returns a reference to the original array. This does not create a new copy of the memory, which means any changes made to the returned array will be reflected directly in the original array.
Grammar:
int* &bar() { static int arr[] = {1, 2, 3}; return arr; }
Practical case:
int main() { int* &arr = bar(); arr[0] = 10; // 更改原始数组值 return 0; }
Features | Return by value | Return by reference |
---|---|---|
The returned copy | is | No |
Changes to the returned array | Do not affect the original array | Reflected directly in the original array |
Memory overhead | Create a copy, the memory overhead is high | Do not create a copy, the memory overhead is low |
Efficiency | Low execution efficiency | High execution efficiency |
The above is the detailed content of What is the difference when a C++ function returns an array?. For more information, please follow other related articles on the PHP Chinese website!