Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a question about passing std::array into function

Tags:

c++

I'm learning c ++ And the syntax of putting a std::array into the function confuses me.

#include <iostream>
#include <array>

using namespace std;

void printArray(const std::array<int, 5> &n)
{
    std::cout << "length: " << n.size() << endl;

    for (int j = 0; j < n.size(); j++ )
    {
        cout << "n[" << j << "] = " << n[j] << endl;
    }

}

int main()
{

    array<int, 5> n = {1,2,3,4,5};

    printArray(n);

    return 0;
}
  1. I want to ask about 'const', what role does it play and what effect does it have if not using it?

  2. Why do we have to use &n while the name of an array is already pointer

like image 692
Quốc Cường Avatar asked Mar 18 '26 14:03

Quốc Cường


1 Answers

Depending on the argument you can do certain assumptions about the function.

void printArrayA(std::array<int, 5> n)

If I call printArrayA then the array I pass to it is copied, so the function can't do changes to the array I pass, but has an overhead of copying the array.

void printArrayB(std::array<int, 5> &n)

If I call printArrayB then the array I pass to it is not copied, the function could do changes on the array, or on the elements stored in the array.

void printArrayC(const std::array<int, 5> &n)

If I call printArrayC then the array I pass to it is not copied, and because it is const the function can't do any changes on that array or on its elements. (Well I, in theory, could cast away the const, but that's not something that should be done, a const should indicate the caller, that the object won't be changed)

like image 193
t.niese Avatar answered Mar 21 '26 04:03

t.niese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!