Search code examples
creturnreturn-valuereturn-type

When should a function return what?


I'm a bit confused about the return type of a function, specifically when to return what. If we have any arbitrary function, let's say min(x,y), which should return according to the if statements, what should I return outside of their scope, which is required by the function's declaration. I've learned that it is common to use "return 0" or "return 1" but I don't understand why that is, and why it can't just return either of the if's return statements.

// compute difference largest - smallest
int   diff(x, y)
{
   if (x > y)
    return x - y;
   if (y > x)
    return y - x;
   if (x == y)
    return 0;
   return 1;
}

Solution

  • The compiler needs to make sure that you return something. If you have returns inside of if statements, such as you have, how is the compiler going to tell if you have covered all cases?

    Even if you do something like the code below, how is the compiler going to know that you will return in all circumstances? Because of that this code will throw an error:

    int min(int x, int y)
    {
        if (x > y)
            return x - y;
        if (y > x)
            return y - x;
        if (x==y)
            return 1;
    }
    

    How can you combat this? You can write another return at the end of the function, as you have. Now the compiler know that you will return a value no matter what happens.

    However there are better ways to make sure that you will always return a value. For example, you can use an else statement as a catch-all:

    int min(int x, int y)
    {
        if (x > y)
            return x - y;
        if (y > x)
            return y - x;
        else
            return 1;
    }
    

    Because the else is guaranteed to catch all cases, the compiler is happy about it, and will not throw any errors.