RAD Studio
ContentsIndex
PreviousUpNext
switch

Category 

Statements 

Syntax  

switch ( <switch variable> ) {casebreakdefault
case <constant expression> : <statement>; [break;]
    .
    .
    .
default : <statement>;
}

Description 

Use the switch statement to pass control to a case that matches the <switch variable>. At which point the statements following the matching case evaluate. 

If no case satisfies the condition the default case evaluates. 

To avoid evaluating any other cases and relinquish control from the switch, terminate each case with break

Example 

This example illustrates the use of keywords break, case, default, return, and switch.

#include <iostream>
        
using namespace std;
        
int main(int argc, char* argv[])
{
  char ch;
        
  cout << "PRESS a, b, OR c. ANY OTHER CHOICE WILL TERMINATE THIS PROGRAM." << endl;
  for ( /* FOREVER */; cin >> ch; )
    switch (ch)
    {
      case 'a' :    /* THE CHOICE OF a HAS ITS OWN ACTION. */
        cout << endl << "Option a was selected." << endl;
        break;
      case 'b' :    /* BOTH b AND c GET THE SAME RESULTS. */
      case 'c' :
        cout << endl << "Option b or c was selected." << endl;
        break;
      default :
        cout << endl << "NOT A VALID CHOICE!  Bye ..." << endl;
        return(-1);
    }
}
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!