Everything but arrays in c++ are passed by value by default?

Viewed 208

Everything in c++ , including the STL containers are passed by value . But the exception is Array which are passed by pointers . Right?

Why are arrays in c++ [eg: int a[5] ] are passed by pointers but the vectors are passed by value ? [By default]

edit: okay , std::array can be passed by value also , I wasn't aware of this .

code :

void fun_array(int a[])
{
    a[0]=10;
}



  void fun_vector(vector<int> v)
    {
        v[0]=10;
    }

    int main()
    {
        int a[5]={1,2,3,4,5};
        vector<int> v={1,2,3,4,5};
        fun_array(a);
        fun_vector(v);

        cout<<a[0]<<" "<<v[0];

    }

output : 10 1

2 Answers

Everything is passed by value if you don't specify otherwise. The case about C arrays is not an exception, but just that they degenerate into pointers. If you need a fixed size array in C++ code prefer using std::array instead of C arrays.

Then decide if you want to pass by value or by reference.

Related note: Even when passing containers, you might still want to pass by value, instead of by reference, if you are going to copy the container.

By default all function arguments in C++ are passed by value.

Your confusion comes from the fact that the name of an array is actually a pointer to the first element of the array (eg. for the array int a[6], a is a pointer to a[0].

Unless the function parameter is explicitly a reference to a pointer, even pointer arguments are passed by value.

Related