Does an else if statement exist?

我的梦境 提交于 2019-11-30 17:59:34

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!