Reputation: 21
I'm learning C language usnig Turbo C++ compiler and just in time I encountered the two statements:
I was wondering if my idea is correct or not that IF (nested with many IFs) and IF-else(not nested) are the same? Suggestions are well appreciated.
Upvotes: 0
Views: 2230
Reputation: 6695
The else if
blocks are in fact nested else
’s since C and C++ don’t have any special support for “elseif” or “elif” concept (not speaking about the preprocessor directives now). It gets obvious with strict use of blocks and indentation:
if(something) { doSomething(); }
else {
if(anotherThing) { doAnotherThing(); }
else {
if(yetAnotherThing) { doYetAnotherThing(); }
else
{ doSomethingElse(); }
}
}
The same code written with the usual else if
notation:
if(something) { doSomething(); }
else if(anotherThing) { doAnotherThing(); }
else if(yetAnotherThing) { doYetAnotherThing(); }
else { doSomethingElse(); }
And as Mateusz Kwaśniak has mentioned, you should prefer switch
over else if
when possible. However, it’s not available for string comparison, for example.
Upvotes: 1
Reputation: 2365
I guess you rather mean if this:
if(expression){
//code
}
else{
if(expression){
//code
}
}
is equivalent to this:
if(expression){
//code
}
else if(expression){
//code
}
and yes it's absolutely the same. Second one is just better looking way of doing this.
Upvotes: 2
Reputation: 2783
That's only basic logic behind that:
Nested if
conditions:
IF first condition's value is true, go into the second condition.
if(a > 0)
{
printf("A is greater than 0\n");
if(a > 2) printf("A is greater than 0 and 2\n");
}
if-else
condition:
IF first condition's value is false, go to the next:
if(a > 0) printf("A is greater than zero\n");
else if(a < 0) printf("A is lesser than zero\n");
else printf("A is zero\n");
There is one more instruction that you should know, switch
:
switch(a)
{
case 0: printf("A is zero\n"); break;
case 1: printf("A is one\n"); break;
case 5: printf("A is five\n"); break;
default: printf("A is not 0, 1 or 5\n"); break;
}
Upvotes: 3
Reputation: 782130
Nested if
is not equivalent to if-else
. It can be equivalent to single if
with a combined condition, for instance:
if (a == 1) {
if (b == 2) {
...
}
}
is equivalent to:
if (a == 1 && b == 2) {
...
}
Upvotes: 2