Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAtanu Mondal
1,976 Pointsgetting compile error while calling EatFly method with if condition checking
while compiling the program i am getting a compile error as
Treehouse.CodeChallenges.Frog.EatFly(int)': not all code paths return a value
Compilation failed: 1 error(s), 0 warnings
below is my complete code
namespace Treehouse.CodeChallenges
{
class Frog
{
public readonly int TongueLength;
public Frog(int tongueLength)
{
TongueLength = tongueLength;
}
public bool EatFly(int distanceToFly)
{
if(TongueLength >= distanceToFly)
{
return true;
}
}
}
}
if i dont use if statement it runs correctly
return TongueLength >= distanceToFly;
can anyone explain why?
namespace Treehouse.CodeChallenges
{
class Frog
{
public readonly int TongueLength;
public Frog(int tongueLength)
{
TongueLength = tongueLength;
}
public bool EatFly(int distanceToFly)
{
if(TongueLength >= distanceToFly)
{
return true;
}
}
}
}
1 Answer
Steven Parker
231,198 PointsDirectly returning the result of the comparison always gives a boolean value, which is consistent with the function definition. This is also an optimum solution to the challenge.
When you add the IF condition, you're only returning a value when the condition is met. To meet the requirements of the definition, you'd also need to a return a value when the condition is not met.