C++ の switch 文における break
 
C および C++ の break ステートメントは、switch ステートメントのコードブロック内で必要な条件が満たされた場合にループが繰り返されるのを防ぐために使用されます。
break ステートメントが使用されていない場合、プログラムは switch ステートメントの終わりに達するまで実行を続けます。
まず、switch ステートメントがどのように機能するかを理解する必要があります。
switch ステートメントの最初に式を指定する必要があります。その後、プログラムは switch ステートメントの各 case を調べ、指定した式に一致するケースが見つかった場合は、そのケースを実行します。
上記のプロセスが式と一致しない場合、プログラムは switch ステートメントからジャンプして default ステートメントを実行します。
C++ での break を含む switch ステートメント
#include <iostream>
using namespace std;
int main() {
  int rating = 2;
  switch (rating) {
    case 1:
      cout << "Rated as 1. ";
      break;
    case 2:
      cout << "Rated as 2. ";
      break;
    case 3:
      cout << "Rated as 3. ";
      break;
    case 4:
      cout << "Rated as 4. ";
      break;
    case 5:
      cout << "Rated as 5. ";
      break;
  }
  return 0;
}
ここでの式は rating = 2 です。ここでプログラムが行うことは、各 case を 1つずつ調べ、提供された式の潜在的な一致をチェックして、ループの実行を停止し、ループを終了して、以下の出力を提供することです。
Rated as 2.
C++ での break のない switch ステートメント
同じコードをもう一度実行してみましょう。ただし、今回は、各ケースの後に break ステートメントを削除します。
#include <iostream>
using namespace std;
int main() {
  int rating = 2;
  switch (rating) {
    case 1:
      cout << "Rated as 1. ";
    case 2:
      cout << "Rated as 2. ";
    case 3:
      cout << "Rated as 3. ";
    case 4:
      cout << "Rated as 4. ";
    case 5:
      cout << "Rated as 5. ";
  }
  return 0;
}
出力:
Rated as 2. Rated as 3. Rated as 4. Rated as 5.
break ステートメントがないと、要件が満たされた後でも、プログラムは各 case の値を出力することがわかります。
break ステートメントは、ループが繰り返される回数が不明な場合、またはループが特定の事前定義された条件を満たしている場合に使用されます。
ステートメント本体に default ステートメントと case 一致がない場合、switch ステートメント本体は実行されません。switch ステートメント本体内には、default ステートメントを 1つだけ含めることができます。
最後に、break ステートメントは、doing、for、while ループでも使用されます。このような状況では、break ステートメントは、特定の基準が満たされたときにプログラムを強制的にループから終了させます。
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.
