Array as function parameter

89 views
Skip to first unread message

Tanupriya Rajput

unread,
Feb 17, 2019, 12:45:36 AM2/17/19
to C++ GCU Forum
Question: To prevent array decay, can we pass an array by reference instead of pass by value?

Or are arrays always passed by reference?

This topic is very confusing and I have never been truly able to understand this.

The article I have referred :

zoso

unread,
Oct 29, 2020, 8:56:11 AM10/29/20
to C++ GCU Forum
The end objective of passing around arrays is...well...to use it at other code sites than the one it was created. So:
1. If you pass an array by allowing it to decay, the resulting "decayed" pointer is still a pointer to a valid memory location. Only thing that inhibits you from writing a regular for loop for iterating over arrays is that you don't know the size since that's lost in the decay. So an obvious workaround is to pass it in along with the pointer. That way, you have access to both the memory and the correct no. of elements to access. This is actually not that uncommon of a pattern in C (though not much in C++) where arrays are passed around in this manner.

2. If you pass in by reference, an obvious necessity is to hardcode the number of elements in the array explicitly because the target function signature needs that size. So that is a sort of a downside to passing by reference.

P.S. There is a way to fix 2 and allow passing arrays by reference without explicitly specifying the number of array elements by using templates but I'll leave it to you to explore it if you want to. Here's an example of all 3 versions https://godbolt.org/z/j87j4P

I hope it makes sense now.

Bansill Creationz

unread,
Oct 29, 2020, 9:12:50 AM10/29/20
to cpp-gc...@googlegroups.com
I am new to this program so couldn't no any of these programs so If you are from the starting of the program please let me know how to do this program

--
You received this message because you are subscribed to the Google Groups "C++ GCU Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cpp-gcu-foru...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/cpp-gcu-forum/4cc0ad77-356c-400d-ac63-bc708c8dc827n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages