user7139569 user7139569 - 29 days ago 16
C++ Question

Why am I getting random numbers in my output?

Please pardon my code as I am fairly new to programming and C++. I am creating a safearray class that checks if the index is out of bounds. I can't figure out why I am getting a random number in my output. I only seem to get the number when the index is out of bounds.

SafeArray.h

#ifndef SafeArray_H
#define SafeArray_H

class SafeArray {
int upperbound;
int lowerbound;
int array[200];
public:
SafeArray(int, int);
int &operator[](int);
void print();
};

#endif


SafeArray.cpp

#include "SafeArray.h"
#include <iostream>
using namespace std;


SafeArray::SafeArray(int l, int u) {
lowerbound = l;
upperbound = u;
for (int i = l; i < u; i++) {
array[i] = 0;
}
}

int &SafeArray::operator[](int index)
{

if (index > upperbound || index < lowerbound)
{
cout << "array out of bounds" << endl;
}
else {
return array[index];
}

}

void SafeArray::print() {
for (int i = lowerbound; i < upperbound; i++) {
cout << array[i] << endl;
}
}


tester.cpp

#include "SafeArray.h"
#include <iostream>
using namespace std;

int main() {
int lowerbound;
int upperbound;
cout << "Enter a lower bound: ";
cin >> lowerbound;
cout << "Enter an upper bound: ";
cin >> upperbound;
SafeArray test = SafeArray(lowerbound, upperbound);
cout << test[101] << endl;
return 0;
}


Output:
Enter a lower bound: 0

Enter an upper bound: 100

array out of bounds

255812108

Press any key to continue. .

.

Answer

The garbage value is because a function MUST return a value unless it was declared void. You left out the return so Crom only knows what will be returned for printing or even if the program will survive to print at all. It is Undefined Behaviour

May I recommend instead

int &SafeArray::operator[](int index)
{

    if (index > upperbound || index < lowerbound)
    {
        throw out_of_range("array out of bounds");
    }
    return array[index];
}

std::out_of_range can be found with #include <stdexcept>

Caller must either catch the exception and carry on or abort. Eg:

try
{
    cout << test[101] << endl;
}
catch(out_of_range & oor)
{
    cout << oor.what() << endl;
}

Now you either get a number or an error message, but never both.