How can I pass a temporary array? I want to do something like this:
#include <iostream>
int sum(int arr[]) {
int answer = 0;
for (const auto& i : arr) {
answer += i;
}
return answer;
}
int main() {
std::cout << sum( {4, 2} ) << std::endl; // error
std::cout << sum( int[]{4, 2} ) << std::endl; // error
}
Do I need a positive integer literal in the function parameter's braces []
? If I include that literal, will it limit what arrays I can pass to only arrays of that size? Also, how can I pass array elements by rvalue reference or const reference? Because the above sample doesn't compile, I presume making the function's parameter type int&&[]
or const int&[]
won't work.