Search code examples
c++arraysfunction

Discrepancy in passing array to function


#include <iostream>
using namespace std;

void myFunction(int myNumbers[5]) {
  for (int i = 0; i < 5; i++) {
    cout << myNumbers[i] << "\n";
  }
}

int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50};
  myFunction(myNumbers);
  return 0;
}

The type of argument that is expected in myFunction is int [5], while the type that is being provided is int*, but the code is working fine! Can someone please explain why?


Solution

  • while the type that is being provided is int*

    No. The type of myNumbers is int[5], array of 5 integers, it is not int*.

    Yes. That array decays to a int*, a pointer to its first element.

    Because it is not possible to pass arrays by value, and because arrays do decay to pointers, the language lets you write void myFunction(int myNumbers[5]) when it actually means void myFunction(int* myNumber).

    You should read about array to pointer decay. And you should not confuse arrays with pointers. An array is not a pointer and a pointer is not an array. And array to pointer decay does not change that.

    TL;DR its a weird oddity inherited from C. Raw arrays are weird.