Search code examples
cif-statementlanguage-lawyersemantics

Does an else if statement exist?


Some time ago after not standing anymore lines like this:

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

I decided for my self its better for readability in our 1920x1200 times, to not omit the {}.

So I wrote a tool that reformats my existing code.

later I noticed a bug in that tool resulting in

if (x)
{
 ...
}
else if(y)
{
 ...
}
else if(z)
{
 ...
}

had been changed (wihtout obvisiously changing the behavior) into:

if (x)
{
 ...
}
else 
{
    if(y)
    {
     ...
    }
    else
    {
        if(z)
        {
         ...
        }
    }
}

This made me realize (unintended) that this is actually what a else if does by syntax and semantical rules of C.

So is there even an statement like else if() existing or is it just an abuse of semantic that results in this usefull but (lets call it so for this purpose) obfuscation originated wording that breaks any formating rules and just serves as human readable?


Solution

  • As per the C11, chapter §6.8.4, selection statements, the available statement blocks are

    if ( expression ) statement
    if ( expression ) statement else statement
    switch ( expression ) statement
    

    and, regarding the else part,

    An else is associated with the lexically nearest preceding if that is allowed by the syntax.

    So, there is no else if construct, exists as per standard C.

    Obviously, an if (or if...else) block can exist as the statement in else block (nested if...else, we may say).

    The choice of indentation , is left to the user.


    Note:

    Just to add, there is no reason for a separate else if construct to exist, the functionality can be achieved by nesting. See this wiki article. Relevant quote

    The often-encountered else if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independent "if then else" statements combined with a particular source code layout. However, this also means that a distinct else-if construct is not really needed in these languages.