painkiller
painkiller

Reputation: 149

How does else interpret the if statements following it?

I have a section of code in C, and I want to understand how does the first else in the program interprets the if that follows it. Usually in an if-else conjunction, when the condition in if is false, the program executes the statement after else, when else has no curly braces. Down bellow, there are no curly braces after else, so my question is: does else interprets "if(prefer>=5) { printf("Buya");printf("Maybe things will get even better soon!\n");}" as a single statement, similar to a " else printf("This is a replacement statement for the aforementioned else");" construction?

Or there is another logic to the if - else if conjunction ? Like, for instance, else activates only the "if(prefer>=5)", and that condition, if true, executes what's in the curly braces ?

The complete code in C is bellow. Thank you in advance.

  #include <stdio.h>

    int main()

    {

        int prefer=2;

        if (prefer >= 8)
        {
            printf("Great for you!\n");

            printf("Things are going well for you!\n");
        }
        else if(prefer>=5)
        {
            printf("Buya");
            printf("Maybe things will get even better soon!\n");
        }
         else if(prefer>=3)
        {
            printf("Bogus");
            printf("Maybe things will get worst soon!\n");
        }
        else
        {
            printf("Hang in there--things have to improve, right?\n");
            printf("Always darkest before the dawn.\n");
        }
        return 0;
    }

Upvotes: 0

Views: 75

Answers (1)

S.S. Anne
S.S. Anne

Reputation: 15576

Here's a more bracketed version that should explain this:

if(prefer >= 8)
{
    ...
}
else
{
    if(prefer >= 5)
    {
        ...
    }
    else
    {
        if(prefer >= 3)
        {
            ...
        }
        else
        {
            ...
        }
    }
}

The else if(condition) ... is not anything special. It is equivalent to else { if(condition) ... }.

Upvotes: 1

Related Questions