- Home /
Not all code paths return a value?
Hello,
This is probably an easy one, but I'm not a very experienced programmer. I understand what the error "Not all code paths return a value" means, but I don't know why I would get it in this case.
I'm creating an inventory system for an RPG from scratch, I have the following function to look for a null space in the inventory array, if it is null, put Item in it. The function will then return a string "Added Item" or "Inventory full." What's wrong here?
public string AddItem(Item addedItem){
for(int i = 0; i < baseInvSize; i++){
if(playerInventory[i] == null){
playerInventory[i] = addedItem;
return "added";
}
else
return "Inventory Full";
}
}
First thing to note, if you're inventory array has 1 item in the first slot and 5 blank slots afterwards, your code reports the inventory as full.
Answer by XGundam05 · Jun 18, 2013 at 03:32 PM
First, you are really only checking the first item in the array with the way you've structured your if
statement.
Second of all, as baseInvSize
is a variable, it's entirely possible for your loop to never be entered.
So really, you want to loop through the array and if you find a null position, add the item and return added
(I'd also use a boolean, but that's irrelevant at this point). If you get through the entire loop and nothing is found, then you return Inventory Full
.
So:
public string AddItem(Item addedItem){
for(int i = 0; i < baseInvSize; i++){
if(playerInventory[i] == null){
playerInventory[i] = addedItem;
return "added";
}
}
return "Inventory Full";
}
Gah! I see. I had my blinders on. I didn't realize that else statement was the downfall of my for loop. Thanks man.
p.s. thanks for the tip about the bool, i've changed that as well.