Home > Enterprise >  Do "else if" exist in c or it just only "if" and "else"?
Do "else if" exist in c or it just only "if" and "else"?

Time:03-03

This might not be a problem but just for peace of mind and I think it good to know how c mechanic deal with this keyword. Consider this,

if (condition1)statement1;
else if (condition2)statement2;

we can interprete as,

if (condition1)statement1;
else statement3;

where "statement3" is "if (condition2)statement2;" Which not violate the c syntax.

In another case, if we added curly-bracket

if (condition1){
    statement1;
}
else if (condition2){
    statement2;
}

Which equivalent to

if (condition1){
    statement1;
}
else {
    if (condition2){
        statement2;
    }
}

Or, if we add more "else if" condition as following.

if (condition1){
    statement1;
}
else if (condition2){
    statement2;
}
else if (condition3){
    statement3;
}
else{
        statement4;
}

We got

if (condition1){
    statement1;
}
else {
    if (condition2){
        statement2;
    }
    else {
        if (condition3){
            statement3;
        }
        else{
            statement4;
        }
    }
}

CodePudding user response:

To answer your question as asked

Do "else if" exist in c or it just only "if" and "else"?

No, else if is not a c keyword. See https://en.cppreference.com/w/cpp/language/if

Note the else statement-false part. Then your following if just becomes that statement-false

  • Related