if / else if / if else

Feb 27, 2017 at 7:23am
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?
Feb 27, 2017 at 7:46am
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;
}

Feb 27, 2017 at 7:47am
Feb 27, 2017 at 8:32am
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.
Feb 27, 2017 at 6:28pm
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?
Feb 27, 2017 at 7:04pm
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.