The loop you've written never modifies X
, so assuming it's a valid array the loop will loop forever (or until it crashes by running some amount off the end).
The C++ way to solve this is to not use arrays but to use std::vector
instead. It keeps track of all the bookkeeping including length for you automatically.
If X is an actual array (like int X[5];
) you can use (sizeof(X) / sizeof(X[0]))
to get the number of elements in the array. If X
is passed as a pointer then there is no way in C or C++ to get the length. You must pass the length along with the array in that case.
You could play games with "magic" numbers in the array that mean end (for example if it must always be positive you could use -1 to signal the end, but that's just asking for obscure bugs. Use std::vector
.