C++/Language/Switch

Материал из C\C++ эксперт
Версия от 10:28, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A switch statement in action

#include <iostream>
using namespace std;
int main(void)
{
   char grade;
   cout << "Enter your grade: ";
   cin >> grade;
   switch (grade)
   {
   case "A":
      cout << "Your average must be between 90 - 100" 
           << endl;
      break; 
   case "B":
      cout << "Your average must be between 80 - 89" 
           << endl;
      break;
   case "C":
      cout << "Your average must be between 70 - 79" 
           << endl;
      break;
   case "D":
      cout << "Your average must be between 60 - 69" 
           << endl;
      break;
   default: 
      cout << "Your average must be below 60" << endl;
   }
   return 0;
}


Deliberately falls through the case

#include <iostream>
using namespace std;
int main(void)
{
   char choice;
   cout << "Choose your car\n";
   cout << "S \n";
   cout << "L \n";
   cout << "D \n";
   cin >> choice;
   cout << "Extra features purchased\n";
   switch (choice)
   {
       case "D":
          cout << "D\n";
       case "L":
          cout << "L\n";
          break;
       default: 
          cout << "None\n";
   }
   return 0;
}


Switch: falling-through behavior

#include <iostream>
using namespace std;
int main(void)
{
   char grade;
   cout << "Enter your grade: ";
   cin >> grade;
   switch (grade)
   {
   case "a":case "A":
      cout << "Your average must be between 90 - 100" 
           << endl;
      break; 
   case "b":
   case "B":
      cout << "Your average must be between 80 - 89" 
           << endl;
      break;
   case "c":
   case "C":
      cout << "Your average must be between 70 - 79" 
           << endl;
      break;
   case "d":
   case "D":
      cout << "Your average must be between 60 - 69" 
           << endl;
      break;
   default: 
      cout << "Your average must be below 60" << endl;
   }
return 0;
}