Search code examples
cif-statementreturnfunction-definition

In c, How does return values work in a function where return values are already added in if statements?


Quick question:

int x;
int y;
int function (int a, int b)
{
   if (x == y)
   {if (y == 1) {return -1;}
    else {return 1;}}
   else {return 1;}
}

why does the code above ask me to add a return value outside of if-else statement and what should I be returning?


Solution

  • I believe it's a general compiler warning and return cases, internally to conditional cases, are not taken into account.

    So, this is what the compiler is "seeing":

    int function (int a, int b)
    {
      if condition
      {...}
      else {...}
    }
    

    ... and the compiler is asking "Where is the return?".

    You can simply add return 0; // not needed, only here for avoiding compiler warnings at the end of your function code and it should be fine.