C ++ Else If


elseifステートメント

最初の条件が。の場合は、ステートメントを使用しelse ifて新しい条件を指定しますfalse

構文

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

int time = 22;
if (time < 10) {
  cout << "Good morning.";
} else if (time < 20) {
  cout << "Good day.";
} else {
  cout << "Good evening.";
}
// Outputs "Good evening."

例の説明

上記の例では、時間(22)は10より大きいため、最初の条件falseです。else ifステートメント内の次の条件 もです。条件1条件2の両方がfalseであるためelse条件に進み、「こんばんは」画面に出力します。false

ただし、時刻が14の場合、プログラムは「Goodday」と出力します。