- Home /
Not all code paths return a value
I've got a function that is returning this error. I can't see where the path is terminating without returning a value. Maybe after numberOfCells++;, but shouldn't it just continue to the next iteration of the for loop?
.
Context: this function should be counting the number of empty cells in a rectangle with the bounds tempStartX, tempStartY and tempEndX, tempEndY by cycling through each cell and checking for empty cells. If it finds any non-empty cells it returns a zero (there is a reason for this). When it reaches the last cell it returns the number of cells. TileType is a 2D array storing the game object that is in each cell.
public int NumberOfExecutableCells_SubModule (int tempStartX, int tempEndX, int tempStartY, int tempEndY){
int numberOfCells = 0;
for (int row = tempStartY; row > tempEndY ; row--){ // Cycle through rows
for (int column = tempStartX; column < tempEndX; column++) { // Cycle through columns
if (TileType[column,row].name != "empty(Clone)"){ // If this cell is not empty
return 0; // Return zero for # of empty cells
}
else{ // Otherwise if this cell is empty
numberOfCells++; // Add 1 to the # of empty cells
if (row == tempEndY && column == tempEndX){ // If this is the last cell
return numberOfCells; // Return the number of empty cells
}
}
}
}
}
Answer by Bunny83 · Jan 05, 2018 at 06:32 PM
First of all this condition will never be true:
if (row == tempEndY && column == tempEndX){
as your for loop conditions will terminate before you reach the end values. The actual issue is simply that a method with a return type always need to return a value. However even your for loops could not run at all depending on the start and end values. So it's possible that the for loops are skipped completely and you just reach the end of your function without returning anything.
In your case it seems to make sense to just remove the condition i've mentioned earlier and move the return statement to the end of the method.
public int NumberOfExecutableCells_SubModule (int tempStartX, int tempEndX, int tempStartY, int tempEndY)
{
int numberOfCells = 0;
for (int row = tempStartY; row > tempEndY ; row--)
{
for (int column = tempStartX; column < tempEndX; column++)
{
if (TileType[column,row].name != "empty(Clone)")
{
return 0;
}
else
{
numberOfCells++;
}
}
}
return numberOfCells;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612145912im_/https://answers.unity.com/themes/thub/images/avi.jpg)