Return NULL in C++

Hello,

I'd like to if a book not find, the below method(findBookByAuthorName) return NULL. or do you have a better idea?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class books
{
	book* myBooks;
	int i;
public:
	books(int n)
	{
		myBooks = new book[n];
		i = 0;
	}
	void addBook(book Book)
	{
		myBooks[i] = Book;
		i++;
	}
book findBookByAuthorName(string name)
	{
		for (int j = 0; j < i; j++)
		{
			if (name.compare(myBooks[j].getAuthor()) == 0)
			{
				return myBooks[j];
			}
		}
	}
}
Last edited on
The return type could be std::otional<book> (requires C++17)

"The class template std::optional manages an optional contained value, i.e. a value that may or may not be present."
https://en.cppreference.com/w/cpp/utility/optional
if for some reason you can't use that ^^ the 2 main alternatives would be to make a bogus book to return or to return the array index as -1 for not found, index if found, make the finder int instead of book type, and then you can call THAT from a more public function that handles the -1 or index in a little wrapper for the user. And I guess you could throw and do try/catch, though I find abusing that for non errors to be a bit of a bad idea.
Last edited on
Provide an output parameter to store the found book, then return a boolean success/fail.
1
2
3
4
5
6
7
8
9
10
11
12
bool findBookByAuthorName(string name, book &result)
	{
		for (int j = 0; j < i; j++)
		{
			if (name.compare(myBooks[j].getAuthor()) == 0)
			{
				result = myBooks[j];
				return true;
			}
		}
		return false;
	}


i is a terrible name for a class member variable.
1
2
3
4
5
6
books(int n)
	{
		myBooks = new book[n]; // what about std::vector?
		numBooks = 0;
		maxBooks = n; // because you need to range check later on
	}


You could also return book{}. Then test with book{} to determine if book found or not.

Last edited on
To return a pointer you'd do:
1
2
3
4
5
6
7
8
9
10
11
12
book *findBookByAuthorName(string name)
	{
		for (int j = 0; j < i; j++)
		{
			if (name.compare(myBooks[j].getAuthor()) == 0)
			{
				return myBooks+j;
			}
		}
		return nullptr;
	}
}


But dealing with raw pointers like this is a landmine of bugs waiting to happen. So any of the alternatives given is preferable.
Last edited on
Topic archived. No new replies allowed.