Nested IF statements vs IF-ELSE

John Counter Source

I'm learning C language usnig Turbo C++ compiler and just in time I encountered the two statements:

  • IF (nested with many IFs)
  • IF-else(not nested but continuing else,else and so on)

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.

c++c

Answers

answered 3 years ago mtszkw #1

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;
}

answered 3 years ago Barmar #2

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) {
    ...
}

answered 3 years ago DawidPi #3

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.

answered 3 years ago Melebius #4

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 possible especially for string comparison.

comments powered by Disqus