Does an else if statement exist?

后端 未结 2 2027
情深已故
情深已故 2021-01-04 06:44

Some time ago after not standing anymore lines like this:

if (arg)
    invk(test);
else if (test)
{
    alot();
    stuff();
}

I decided fo

2条回答
  •  情书的邮戳
    2021-01-04 07:42

    As every one is aware, there is several different styles of programming languages. The presence of a elseif is based on the style of language. In a C/Pascal style the if statement is

    if (...)
       statment; 
    else
       statement;
    

    and you have a compound statement: { statment; statment; }

    while in a Modula2 / VB / (python ?) style language you have

    if (...)
       statement;
       ...
       statement;
    else
       statement;
       ...
       statement;
    end-if
    

    in the Modula2 / VB you need a elseif statement because if you tried using else if you get

    if (..)
    else if (..)
    else if (..)
    end-if; end-if; end-if;
    

    The end-if's at the end are rather ugly.

    As @anatolyg noted this is why you have a #elif in C macro language.


    Cobol-85 has a different take on the elseif statement. It provides an extended Select/case statement. In Cobol you have an evaluate:

    evaluate option
       when 1
          ...
       when 2
          ...
    

    but you can also do

    evaluate true
       when age > 21 and gender = 'male'
          ...
       when age > 21 and gender = 'female'
    

    In Cobol you can also mix the case and if structure

    evaluate option also true
       when 1 also age > 21 and gender = 'male'
          .... 
       when 1 also age > 21 and gender = 'female'
          .... 
       when 2 also any
          ....
    

    One final point in java and C you sometimes see

    if () {
    
    } else if () {
    
    } else if () {
    
    }
    

    To all intents and purposes, this is VB / Modula-2 written in Java/C.

提交回复
热议问题