jeudi 28 décembre 2017

C++ Statement can be simplified

Apologies for the lame question. I am using Intellij Clion Student licensed version for my C++ curriculum. As a part of implementing an UnsortedList class, we had to write a method isInTheList to see if an element is present in the array. The class implementation goes as

bool UnsortedList::isInTheList(float item) {

    for (int i = 0; i < length; i++) {
        if (data[i] == item) {
            return true;
        }
        return false;
    }
}

However, the ide shows a coloured mark at data[i] == item with a popup saying

Statement can be simplified less... (Ctrl+F1) 
This inspection finds the part of the code that can be simplified, e.g. constant conditions, identical if branches, pointless boolean expressions, etc.

For a previous method to check if the list if empty, I used the following simplified form instead of if-else statement.

bool UnsortedList::isEmpty() {
    return (length == 0);
}

However, with iteration involved now, I cannot come up with a simplified statement in the former. Any help is much appreciated. Thank you.

Aucun commentaire:

Enregistrer un commentaire