Is there any appreciable difference between if and if-else?

前端 未结 9 892
执笔经年
执笔经年 2021-01-12 06:55

Given the following code snippets, is there any appreciable difference?

public boolean foo(int input) {
   if(input > 10) {
       doStuff();
       retur         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 07:45

    In your case the second if would only get called if the first if failed so it's less important here but if your first if did something and didn't return, the second if (which would then always be false) would still be tested unless it was in an else-if.

    In other words, there are cases where the difference between if-else-if and if-if matters, but this isn't one of them.

    Example: Try this and then try it after removing the else. You get two different outputs:

    int someNumber = 1;
    if(someNumber < 5)
    {
        someNumber += 5;
        Console.WriteLine("First call.");
    }
    else if(someNumber >= 5)
    {
        Console.WriteLine("Second call.");
    }
    

提交回复
热议问题