Search code examples
c++arrayspost-incrementfunction-parameter

What does arr++ mean in a function "int f(int arr[])"?


I was looking at this code and understood pretty much all of it except one thing:
what does Arr1++ means?

What does it do to the array? since Arr1 is not just a normal variable like int..

bool theSameElements(int Arr1[], int Arr2[], int size)
{
    int temp;
    if (size == 0)
    {
        return true;
    }
    for (int i = 0; i < size; i++)
    {
        if (Arr1[0] == Arr2[i])
        {
            temp = Arr2[i];
            Arr2[i] = Arr2[0];
            Arr2[0] = temp;
            Arr1++;
            Arr2++;
            return theSameElements(Arr1, Arr2, size - 1);
        }
    }
    return false;
}

Solution

  • Any array passed as function parameter is implicitly converted / decays to a pointer of type int*. Now the Arr1 is a pointer pointing to the first array element namely Arr1[0]. This is known as the Array-to-pointer decay. Applying the post-increment operator:

    Arr1++;
    

    increments the pointer value by the size of the data it points to so now it points to the second array element Arr1[1].

    That being said you should prefer std::array to raw arrays and smart pointers to raw pointers.