if / else if / if else

closed account (G2UR4iN6)
So today someone told me there is no function called else if, is that true?

I know if exists
Else exists

But else if does it exist?
Else if exist, and it's used to test another condition.
https://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm

Sample code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main(){

	int num;
        cout << "Enter a number: ";
	cin >> num;
	if(num == 1){
		cout << "The number is 1"; 
	}
	else if(num == 2){
		cout << "The number is 2";
	}
	else{
		cout << "The number is not 1 or 2";
	}
    return 0;
}

It's possible that they were trying to be a wise...burro in that an "else if" is technically a statement rather than a function.

It definitely does exist.
Lets pretend that there is no separate else if.

We can have a conditional statement construct FOO:
if ( cond2 ) { statement2; } else { statement3; }

Then we have actual conditional construct in our code:
1
2
3
4
if ( cond4 ) {
  statement4;
}
else statement5;


It should be perfectly legal to use FOO as statement5:
1
2
3
4
if ( cond4 ) {
  statement4;
}
else if ( cond2 ) { statement2; } else { statement3; }

reindent:
1
2
3
4
5
6
7
8
9
if ( cond4 ) {
  statement4;
}
else if ( cond2 ) {
  statement2;
}
else {
  statement3;
}


You can easily test whether the compiler allows such syntax.
Does it matter whether the apparent "else if" really is or just looks and behaves like?
depends on how technical you are.

if ()
{

}
else
{
if() //not else/if but functionally identical
{

}
}

which, if the programmer does not use {} for one liners, can be disguised:

if()
stuff;
else if () //disguised above structure looks like else-if but its 2 statements on one line, is all.

Doesn't matter practically, as you can DO else-if in practice. Its just whether someone wants to get really picky about the details.





Topic archived. No new replies allowed.