Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different between if else and return

My first snippet:

public bool isSmall(int x)
{
    if (x == 0)
    {
        return true;
    }
    else
    {
        if (x < Smallest)
        {
            return true;
        }
        else
        {
            return false;
        }
     }
}

My second snippet:

public bool isSmall(int x)
{
    if (x == 0)
    {
        return true;
    }

    if (x < Smallest)
    {
        return true;
    }

    return false;
}

What I want is if (x == 0) to just return true, if not do another comparison, if (x < Smallest), and if true return true, otherwise return false. I know my fist and second code do the same thing, but I am wondering which way to write it is better, affection, and safe? do they have any real differences? Or is it just two ways to write it?

like image 446
Yode Zage Avatar asked Jul 20 '26 03:07

Yode Zage


2 Answers

The compiler will probably optimize either one of your routines to the following:

public bool IsSmall(int x)
{
   return (x == 0 || x < Smallest);
}

To see why, write out & fill in a Boolean truth table for each set of methods.

like image 156
Daniel A. Thompson Avatar answered Jul 21 '26 15:07

Daniel A. Thompson


They do the same thing. The second one could be slightly more efficient if the code was compiled directly as written (since there is one less branch statement because of the omitted else). However, all modern compilers will optimize this so that they are exactly the same.

To answer your question (which is better), whichever is easier for you to read and understand is better since they do the same thing.

like image 31
nhouser9 Avatar answered Jul 21 '26 17:07

nhouser9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!