user949358
user949358

Reputation: 113

Getting error: control reaches end of non-void function dont know why

I keep receiving the following error and I have no idea whats wrong

cc1plus: warnings being treated as errors
scene.cpp: In member function ‘Image* Scene::getpicture(int) const’:
scene.cpp:179: error: control reaches end of non-void function

Here is the part of the code that the error is in:

Image* Scene::getpicture(int index) const {

    if(index<0 || index >maximum)
        cout << "invalid index" << endl;
    else {
        return images[index]; 
    }
}

Upvotes: 1

Views: 6792

Answers (2)

Jesper
Jesper

Reputation: 206956

When the condition of the if statement is true, then the function doesn't return a value, because there is no return statement that's executed in that case.

You need to return a value (or throw an exception). For example:

Image* Scene::getpicture(int index) const {
    if (index < 0 || index > maximum) {
        cout << "invalid index" << endl;
        return NULL;  // Return NULL in case of an invalid index
    } else {
        return images[index];
    }
}

Upvotes: 3

Mysticial
Mysticial

Reputation: 471529

If the code does not enter the else statement, nothing gets returned. Therefore you need to insert a return either at the end or when you enter the if-statement.

Upvotes: 7

Related Questions