In which case, this function will not return a value? Why does the compiler report an error?

public static int Test(int n)
{
  if (n < 0) return 1;
  if (n == 0) return 2;
  if (n > 0) return 3;
}

The compiler (Visual Studio 2010, C # 4.0) says: "Not all code paths return a value." Why?

+5
source share
4 answers

The compiler does not look at your conditions. Even if you are right that at least one of your if-blocks will be launched, you still have to reorganize something like this:

if (n < 0)
    return 1;
else if (n == 0)
    return 2;
else
    return 3;
+8
source

, n. , , , if, , ... , .

. , .

.

+10

, , , , if .

if else else , . .

+2
source

The compiler does not know that you used all of your databases. You can rewrite it like this ...

public static int Test(int n)
{
  if (n < 0) return 1;
  else if (n == 0) return 2;
  else (n > 0) return 3;
}

or that...

public static int Test(int n)
{
  if (n < 0) return 1;
  if (n == 0) return 2;
  if (n > 0) return 3;
  return 4; //will never occur
}
+1
source

All Articles