If you write non-trivial code, you should really watch out to write clean code, and use container classes and
range-for[
^] instead of C arrays and index based loops.
E. g. your function could be rewritten in a much safer way like this:
size_int Length() {
size_int len = 0;
for (auto temp : data) {
try {
len++;
} catch (...) {
break;
}
}
return len;
}
This obviates the need for the try block too, unless the type size_int might throw upon calling the increment operator.
Note that this even works with a C array, unless you allocated it on the heap.
If all you want is the length of the array, you could also use std::begin() and std::end() to determine the range. Here are examples for the last two suggestions:
#include <iostream>
struct test {
int data [4];
size_t len1() {
size_t l = 0;
for (auto tmp : data)
++l;
return l;
}
size_t len2() {
return std::end(data) - std::begin(data);
}
};
int main()
{
test t;
std::cout << t.len1() << "\n";
std::cout << t.len2() << "\n";
return 0;
}
This will print 4, twice.
Of course, if you allocated this array dynamically, using new[] or malloc, than the only way to obtain the array size is saving this information at the time when you allocate the array! But if that is what you do, you really should use std::vector instead!