I noticed that there was no if-elseif-else syntax in C language.

Embarrassingly

I usually write C language (and C ++) for more than 6 years because there was no problem even if the else if that appears in the conditional branch of C language is the same as els if in Ruby. However, I now understand the meaning of else if.

Main subject

The beginning is the omission of curly braces

if(Conditional expression) {
then clause;
} else {
else clause;
}

If the content of the else clause is one line, omit the curly braces.

if(Conditional expression) {
then clause;
}else else clause;

You can write that.

In short

if(hoge == piyo){
    fuga = 1;
}else{
    fuga = 2;
}

To

if(hoge == piyo){
    fuga = 1;
}else fuga = 2;

It means that you can write.

That means ...

if(Conditional expression) {
then clause;
} else {
    if(Conditional expression) {
then clause;
    } else {
else clause;
    }
}

Is

if(Conditional expression) {
then clause;
} else if(Conditional expression) {
then clause;
    } else {
else clause;
    }

Will be written.

If you adjust the indent

if(Conditional expression) {
then clause;
} else if(Conditional expression) {
then clause;
} else {
else clause;
}

It will be a familiar shape.

Rough summary

There were only if and else in C language, huh ~. On the contrary, it is interesting because it is easier to see by not adding indentation on purpose.

Recommended Posts