Home  >  Article  >  Backend Development  >  What is the difference when a C++ function returns an array?

What is the difference when a C++ function returns an array?

PHPz
PHPzOriginal
2024-04-19 21:06:02659browse

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.

C++ 函数返回数组时有什么区别?

#Differences when C functions return arrays

In C, functions can return various types of data, including arrays. When a function returns an array, there are two different behaviors:

  • Return by value: Returns a copy of the array to the caller.
  • Return by reference: Returns a reference to the array, not a copy.

Returning by value

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 by reference

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;
}

Difference

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn