The parameter int numbers[] is actually a pointer, not an array. Range-based loops do not work on pointers.
If you have a C-style array that for whatever reason you need to pass safely to a function, you can use a function template. This allows the compiler deduce the array size from its type.
#include <cstdint>
#include <iostream>
template <std::size_t size>
int * decrementArrayElements(int (&numbers)[size])
{
for (int &x : numbers) --x;
return numbers;
}
int main()
{
int numbers[] = { 1, 2, 3, 4 };
decrementArrayElements(numbers);
for (int x : numbers) std::cout << x;
}
Outputs:
0123
In this case the pattern of returning a pointer probably isn't all that useful. It's more likely to be abused. I would lean towards making the function void.
You may want to consider using std::array instead, which has better encapsulation and (unlike C-style arrays) has copy semantics consistent with other types.
#include <array>
#include <cstdint>
#include <iostream>
template <std::size_t size>
std::array<int, size>& decrementArrayElements(std::array<int, size>& numbers)
{
for (int &x : numbers) --x;
return numbers;
}
int main()
{
std::array<int, 4> numbers = { 1, 2, 3, 4 };
decrementArrayElements(numbers);
for (int x : numbers) std::cout << x;
}
forstatement doesn't work, because the compiler doesn't know how many elements there are. That's why you should be using std::vector.