Thread: Usefulness of the "else if" statement

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    5

    Usefulness of the "else if" statement

    Hey guys. I started learning C today, and so far, the material has been fairly logical and pretty straight forward (if not a little overwhelming because of the jargon). I just finished the second tutorial on C, and learning about "if" statements has been fun and challenging at the same time to me as there are many ways to play around with the conditions of the statements that make them true. Anyway, I've been thinking about one particular thing: the "else if" statement.

    The main thing that troubles me is its usefulness. Why use the "else if" if you can just put another "if" statement in there? For example, the second C tutorial of the site gives me the following code. I want you to pay attention to the bold parts, specifically:

    Code:
    #include <stdio.h>	
    
    int main()                            
    {
        int age;                        
      
        printf( "Please enter your age" );  
        scanf( "%d", &age );                
        if ( age < 100 ) {               
         printf ("You are pretty young!\n" ); 
      }
      else if ( age == 100 ) {
         printf( "You are old\n" );       
      }
      else {
        printf( "You are really old\n" );     
      }
      return 0;
    }
    So if I input '100,' it'll give me "You are old!"
    Clearly, it seems to me that the bold parts of the code can also be written as:

    Code:
    ...
    if (age < 100)
    ...
    if (age == 100)
    ...
    According to the conditions of the "else if" statement, if the first statement is true, then it will be ignored. And by contrast, if the first statement is false, then it will be checked. Changing the "else if" statement to an "if" statement here seems to yield the same result anyway ("You are old"), so I wonder why it's even necessary at all.

    Since I'm a novice at this, I probably don't have sufficient understanding of the features of the language to understand the intricacies of such topics (or I'm completely missing something here), but I can't shake this curiosity. Could you explain to me or give me some examples of code where changing an "else if" statement to an "if" statement would not work or would make the situation horribly tedious or inefficient? Thanks for reading. I know I tend to ramble quite a lot.

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    There is no real "else if" statement in C. Consider the following:

    Code:
    if(x == 0) printf("Warning!  X is 0!\n");
    That code is perfectly valid (assuming x has been previously declared, etc.) because an if statement, if its condition is true, will execute the next statement.

    The else part of an if clause is the same way:

    Code:
    if(y != 0) printf("y is not 0\n");
    else printf("y is 0\n");
    The else part will execute only the next statement should the condition of the original if statement be false.

    So hence:

    Code:
    if(x == 0) ....
    else if(x == y) ....
    else ....
    Is really expanded like this:

    Code:
    if(x == 0)
    {
            ....
    }
    else
    {
            if(x == y)
            {
                    ....
            }
            else
            {
                    ....
            }
    }
    I rushed this, but if I didn't make a mistake, both forms are equivalent.

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Imagine a very large if/else block like this:
    Code:
    if ( n == 1 ) {...}
    else if ( n == 2 ) {...}
    else if ( n == 3 ) {...}
    else if ( n == 4 ) {...}
    ...
    else if ( n == 100 ) {...}
    If n is 1, it will match the first if clause and will skip all the else if statements.

    If however, you wrote only if statements:
    Code:
    if ( n == 1 ) {...}
    if ( n == 2 ) {...}
    if ( n == 3 ) {...}
    if ( n == 4 ) {...}
    ...
    if ( n == 100 ) {...}
    Then if n is 1, it will still evaluate all 99 other if statements which is a complete waste of time.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > Why use the "else if" if you can just put another "if" statement in there?
    The else if construct stops when the first true condition is found.

    Code:
    if ( grade == 'a' )
    else if ( grade == 'b' ) 
    else if ( grade == 'c' )
    
    Against
    if ( grade == 'a' )
    if ( grade == 'b' )
    if ( grade == 'c' )
    If the grade was 'b', then using else if, the grade == 'c' comparison is skipped, because a successful match was made.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Could you explain to me or give me some examples of code where changing an "else if" statement to an "if" statement would not work
    Fine.
    Code:
    list *merge( list *a, list *b )
    {
      struct node aux;
      list *temp = &aux;
      
      while ( b != NULL )
        if ( a == NULL )
        {
          a = b;
          break;
        }
        else if ( a->data >= b->data )
        {
          temp = temp->next = a;
          a = a->next;
        }
        else
        {
          temp = temp->next = b;
          b = b->next;
        };
        
        temp->next = a;
        return aux.next;
    }
    A simple merge.

    While you could write the algorithm in logically equivalent ways, else if is a requirement in this particular merge because we must make sure that a and b point to valid locations before dereferencing either of them as part of the comparison of a and b. We don't know how to merge a just because it points to a location, and you cannot make a further test in all cases.

  6. #6
    Registered User
    Join Date
    Aug 2007
    Posts
    5
    Ah. I think I understand now. Thank you very much for the examples and the explanations. (Though, I'm way too low of a level to be able to comprehend citizen's example, but it helps that he gives me an example where "else if" is quite necessary and isn't simply a matter of efficiency)

    I was experimenting, and there's something that I want to run by you guys once more. I created a (rather sloppy) program, and found something interesting.

    Code:
    #include <stdio.h>
    
    int main()
    {
        int x;
        printf ("Insert a number between 1-3: ");
        scanf ("&#37;d", &x);
        if (x == 1)
           printf ("x is one.");
        else if (x == 2)
           printf ("x is two.");
        else if (x == 3)
           printf ("x is three.");
        else
            printf ("x is not one, two, or three.");
        return 0;
    }
    Input: 1 --> x is one
    Input: 2 --> x is two
    Input: 3 --> x is three
    Input: 4 --> x is not one, two, or three.

    I also tried changing all of the "else if" statements to "if" statements, and it gave me different results:
    Input: 1 --> x is one.x is not one, two, or three.
    Input: 2 --> x is two.x is not one, two, or three.
    Input: 3 --> x is three.
    Input: 4 --> x is not one, two, or three.

    It seemed really peculiar, but when I looked at MacGyver's explanation of how ifs/thens are expanded, it makes sense. It goes something like this, right?
    Code:
    if(x == 0) ....
    else if(x == y) ....
    else if(x == z) ....
    else ....
    expands to...
    Code:
    if (x == 0) ....
    {
          ....
    }
    else
    {
        if (x == y)
        {
              ....
        }
        else
        {
            if (x == z)
            {
                  ....
            }
        }
    }
    This seems consistent with my example programs. In the "else if" version, if '1' or '2' is the input, then it will skip all of else(/ifs) after it, which is why, when given '1' or '2', it gives "x is 1 (or 2)" as the output without the "x is not one, two, or three" string after it. It looks to me like a tree of if/thens. The first "if" has a branch, which is the first "else if," and this "else if" has another branch, which is another "else if," etc. However, with the "only if" version, all three "ifs" are on different parts of the tree, which would explain why it gives me an output like "x is one.x is not one, two, or three." The "only if" version evaluates all three of the conditions. With '1,' it evaluates "if (x == 1) as true, so it proceeds with that. if(x == 2) is false, so it skips it, and if(x == 3) is also false, which explains why it goes to the "else" statement. (It looks like in this scenario, the else statement belongs to the if(x == 3) branch because it comes right after it). This seems like a delicate subject because I'm so early on (You don't want to build a house on a faulty foundation, right?), so I wanted to make sure that I have my ideas on the right track.

    Again, I am very thankful.

  7. #7
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    Well else if can let the program skip doing unnecessary evaluations, because if one if-case is true then the following else ifs will be ignored. It can also help reading your code since when you're having a series of else ifs you know that they depend on a former if-statement and is in some way related. With a series of ifs this would be harder to see at a glance, unless you have some quirky indentation style.
    Another thing is that with else ifs you know that the previous if-statements were already false, so you don't need to evaluate them again. Successive if-statements will be executed whether or not the previous one failed. To extend on the age program:
    Code:
    /* With only if-statements */
    if (age < 20)
      puts("...");
    if (age >= 20 && age < 50) /* Note that age >= 20 is the same as !(age < 20) */
      puts("...");
    if (age >= 50 && age < 75)
      puts("...");
    if (age >= 75)
      puts("...");
    
    /* With else */
    if (age < 20)
      puts("...");
    else if (age < 50) /* Don't need to check if age >= 20 is true because if it wasn't */
      puts("...");     /* this would never be evaluated in the first place. */
    else if (age < 75)
      puts("...");
    else
      puts("...");
    When it's impossible to use only ifs? I think, as my mental abilities deteriorate when I'm staying awake for too long, that it's never impossible as long as you stay within the frames of functional programming. That is you're not doing things that cause side effects, or manipulating a state while you're performing checks and such.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    OnionKnight mentions a good example, something like this:

    Code:
       .... 
       if (state == started) state = running;
       else if (state == running) do_something(); 
       else state = started;
    Since we modifiy the state in the if-statement, the second if statement (without else) would cause the call to "do_something();" to happen NOW. If that's not the right thing to do here, we definitely need the "else if" configurtion.

    --
    Mats

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. too many "else if" statements
    By xwielder in forum C++ Programming
    Replies: 8
    Last Post: 11-10-2006, 09:34 PM
  2. Meaning of this statement?
    By @nthony in forum C Programming
    Replies: 7
    Last Post: 07-16-2006, 02:57 AM
  3. If Else statement problem
    By doofusboy in forum C Programming
    Replies: 2
    Last Post: 11-09-2005, 07:18 AM
  4. if/break statement
    By Apropos in forum C++ Programming
    Replies: 7
    Last Post: 02-22-2005, 02:33 PM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM