-2

This a Method I am using with my Program

static int check(int pos) {
    int i, flag = 0;
    for (i = 0; i < pos; i++) {
        if (a[pos] == a[i]) {
            flag = 1;
            return 1;
        }
    }
    if (flag == 0)
        return 0;
}

When I compile it, I get the following Error:

Distinct.java:16: error: missing return statement
}
^
1 error

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Daniel Raj
  • 11
  • 1
  • 4
  • The flag is unnecessary. Just return 1 from the loop when you get a match and return 0 at the end of the function. – JJJ Jun 30 '17 at 12:17
  • You should indent your code properly if you are asking people to try and read it. – khelwood Jun 30 '17 at 12:18
  • the compiler just found a path that is not returning anything: if the condition of the last `if` is false there is no return - the compiler did not figure out that flag will always be zero there... – user85421 Jun 30 '17 at 12:29

1 Answers1

1

what would happen when neither

if (a[pos] == a[i]) 

nor if (flag == 0) conditions are met?

then you have a code that is not covering all possible cases, your method have to return something no matter which condition met!!

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • and your return is inside an if condition.... – ΦXocę 웃 Пepeúpa ツ Jun 30 '17 at 12:21
  • 1
    If the first condition is never met, then flag is always 0 so the program can't reach the end of the function without a return statement. Of course the compiler doesn't analyze the code this far so it can't know that. – JJJ Jun 30 '17 at 12:21
  • This Method is to check whether the Element postion passed has the same element before it . Return 1 says the element is present (that is Duplicate Element before the position 'pos') . Return 0 says that the element is not present(that is it is a Unique Element) – Daniel Raj Jun 30 '17 at 12:22