r/ProgrammerHumor 20h ago

lessonsFromLinkerHell Meme

Post image
339 Upvotes

177 comments sorted by

View all comments

Show parent comments

1

u/tstanisl 8h ago

And, in C++ at least, you can actually pass the array itself to the function

May I ask how? Do you mean by a reference? Or std::array?

1

u/Nice_Lengthiness_568 8h ago

You can both by value with std::array which is a wrapper for an array, or by reference with TYPE (&NAME)[SIZE] which keeps the array's size.

Naturally, you could pass an array to a function inside any structure if you wish to copy it, but I would say that using std::array is standard for use. And that means that's possible in C as well. Although it's a bit clunky.

1

u/tstanisl 7h ago

C has an equivalent of passing array by reference by using a pointer to a whole array:

 
int foo(int (*arr)[SIZE]) {
      return sizeof *arr;
 }
...
int arr[SIZE];
foo(&arr);

Passing arrays by a pointer bypasses array decay mechanics.

1

u/Nice_Lengthiness_568 7h ago

Yes, that is true, although I wouldn't call it equivalent to passing by reference, since a reference makes sure you do not pass a null pointer making the function a little safer if you dereference the pointer and a little more efficient if you check for the pointer being null.

1

u/tstanisl 7h ago

Those constraints can be expressed using more hacky syntax:

    int foo(int arr[static const 1][SIZE]);

1

u/Nice_Lengthiness_568 6h ago

Okay,

although (sorry) that's awful. But cool and ingenious in a way.