I'm trying to learn C++ but I just can't wrap my head around this code here, despite spending a good amount of time searching for an answer:
#include <iostream>
void printArray1(int (&array)[3]) {
for(int x : array)
std::cout << x << " ";
}
void printArray2(int array[]) {
for(int x : array) // compiler error, can't find begin and end
std::cout << x << " ";
}
int main() {
int a[3] = {34,12,88};
for(int x : a)
std::cout << x << " ";
std::cout << std::endl;
printArray1(a);
printArray2(a);
std::cout << std::endl;
return 0;
}
In printArray1, we are receiving a parameter that is a reference to an array of size 3. Does this mean we are receiving the address of the entire array or are we just receiving an address to the first element in the array of size 3? Also, how is this parameter then passed to the loop?
In printArray2, we are receiving a pointer to the first element in the array, correct? In other words, we are also receiving an address just like in printArray1? Thus, the ranged-based for-loop in this function will not compile because we have no size data for the array, right?
Finally, when we attempt to print with the ranged-based for-loop in main, what exactly are we passing to the loop? Is it a pointer to the first element in the array here, and if so, why does it compile if the for-loop in printArray2 did not accept the pointer?
My understanding of C++ is still quite elementary so I really appreciate the help, thank you!