Searching Algorithm Warning

I put the warnings in comments on the lines where they occur.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
BibEntry findEntry(ArrayList<char> a){ //searches for BibEntry a
	if(base == NULL) throw ele;
	BibEntry& temp = *base;
	bool found = false;
	
	if(temp.getTag() == a) {
		found = true;
		return temp;
	}
	else {
		while(temp.getTag() != a && temp.getNext().address() != NULL) {
			if(temp.getNext().getTag() == a) {
				found = true; //this never happens
				return temp;
			}
			else
				temp = temp.getNext();
		}
	}
	
	if(!found) throw EntryNotFoundException(); //found is always false
}


The only cause I can think of is that the compiler sees the return statement and stops reading. How should I fix this? Do I even need to worry about this?
You haven't even told us the warning...
The warnings are explained by the comments in the code.
//this never happens Fals. This does happens, but next line will stop the function, making assigment useless.

if(!found) throw EntryNotFoundException(); //found is always false  
There is no way for found to be true here: every path which would set it to true also returns from function. Actually if it could, it would be even more dangerous: function would reach end and not return anything, potentially wrecking whole program.

So these warning suggest you how to optimise your function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
BibEntry findEntry(ArrayList<char> a)
{ 
	if(base == NULL) throw ele;
	BibEntry& temp = *base;
	if(temp.getTag() == a)
		return temp;
	else {
		while(temp.getTag() != a && temp.getNext().address() != NULL) {
			if(temp.getNext().getTag() == a) 
				return temp; //Should you really return temp and not temp.getNext()?
			else
				temp = temp.getNext();
		}
	}
	throw EntryNotFoundException(); 
}


And think about other ways to report not found entities aside from throwing exception. They are not to be used for normal control flow (unless "not found" is a serious situation which warrants program termination).
Ok, I decided to rewrite my function as such:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
BibEntry findEntry(ArrayList<char> a) {
	if(base == NULL) throw EmptyArrayException();
	BibEntry& temp = *base;
	
	if(temp.getTag() == a) {
		return temp;
	}
	else if(temp.getNext().address() == NULL) {
		throw EntryNotFoundException();
	}
	else {
		return findEntry(temp.getNext().getTag());
	}
}


Will this work?
Will this work?

Probably, and the compiler might optimize away the recursion, but why not just do it in a loop?
1
2
3
4
5
6
7
BibEntry findEntry(ArrayList<char> a) {
	if(base == NULL) throw EmptyArrayException();
	for (BibEntry* temp = base; temp; temp = &temp->getNext()) {
		if (temp->getTag() == a) return *temp;
	}
	throw EntryNotFoundException();
}
Topic archived. No new replies allowed.