foreach in C++ int array
An array (a raw array) decays into a pointer when passed as an argument to a function, so your array has no size information.
You need to pass the length of the array explicitly into the function to know it inside the function.
Alternatively, and better, use a std::vector
and then you'll have the .size()
always available when needed.
You're using concepts of C# in C++ but, even if we assume that both languages are similar, they're not equal.
The syntax for a ranged-for in C++ is the following:
for (type identifier : container) // note the ':', not ';'
{
// do stuff
}
You can use this for flavour if you have a C++11 compiler.
Btw, it seems that you're using properties on your code:
for(int x = 0 ; addons.length;++x) // what is lenght?
{
std::cout<< addons[x];
}
There's no such thing in C++, if you want to call an object method you need to call it as a function:
// assuming that the object 'addons' have a method
// named 'length' that takes no parameters
addons.length();
But the addons
variable isn't an object, is an array (take a look to this tutorial), so it doesn't have a method or property named length
; if you need to know its length in order to iterate it you can use in some contexts the sizeof
operator (see the tutorial for more information).
Let's suppose that addons
were a container:
typedef std::vector<addon> Addons;
Addons addons;
If you want to iterate it using the C++11 range-for, you can write it as follows:
for (addon a : addons)
{
// do stuff with a.
}
Hope it helps.
Apart from using vectors, as Tony suggests, you can use templates and pass the array by reference so that the compiler will deduce the array's size:
template<int N>
void testFunction(int mainProd,int (&addons)[N])
{
for(int x = 0; x < N; ++x) // ---- working
{
std::cout<< addons[x];
}
}