RAD Studio
ContentsIndex
PreviousUpNext
case

Category 

Statements 

Syntax  

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

Description 

Use the case statement in conjunction with switches to determine which statements evaluate. 

The list of possible branch points within <statement> is determined by preceding substatements with

case <constant expression> : <statement>;

where <constant expression> must be an int and must be unique. 

The <constant expression> values are searched for a match for the <switch variable>. 

If a match is found, execution continues after the matching case statement until a break statement is encountered or the end of the switch statement is reached. 

If no match is found, control is passed to the default case.

Note: It is illegal to have duplicate case
constants in the same switch statement. 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!