1

This may be a stupid question, but I just want to somebody can give a better explanation.

I have a method defined as below:

    private int Test(int i)
    {
        if (i < 0) return -1;
        if (i == 0) return 0;
        if (i > 0) return 1;

        //return 0;        
    }

It gives me this error "not all code path return a value".

I thought I had 3 if statement, which could cover all the scenarios(i<0, i==0, i>0). So it should not show me this error.

3
  • 2
    By the way, you could replace this method with Math.Sign(i). Commented Apr 10, 2020 at 7:41
  • 3
    Yes, the compiler is not smart enough to get that in case of int i all scenarios are covered; as an excuse of the false alert, please, note that for double i the warning is correct (double.NaN will pass all three ifs) Commented Apr 10, 2020 at 7:42
  • @DmitryBychenko, thank you, and also let me know another scenario double.NaN. Commented Apr 10, 2020 at 8:02

3 Answers 3

5

The compiler just ain't that clever. Also, you're code is slightly inefficient in that it tests for a certainty (i must be greater than zero in the last case).

Write it as:

private int Test(int i)
{
    if (i < 0) return -1;
    else if (i == 0) return 0;
    else return 1;
}
Sign up to request clarification or add additional context in comments.

Comments

3

During compile-time, the compiler doesn't analyze the conditions and understands that they cover all the options - it just sees three unrelated if statements, and a path with no return if none of them are triggered.

You can make it "understand" by using else if and elses:

private int Test(int i)
{
    if (i < 0) return -1;
    else if (i == 0) return 0;
    else return 1;        
}

Comments

-1

If you want to keep your format, a way to do it is like this...

private int Test(int i)
{
   bool result = 1;

   if (i < 0) result = -1;
   if (i == 0) result = 0;
   if (i > 1) result = 1; //This is redundant because i is initialized to 1

   return result;
}

2 Comments

I wouldn't allow this code past a code review. It is inefficient and difficult to read.
@JasperKent Maybe in this case is a bit inefficient (after all it can be done in one line) but I do not believe it is difficult to read. I think there are cases that this may come handy...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.