Switches

This is a discussion on Switches within the C++ Programming forums, part of the General Programming Boards category; Can any one give an example of a switch?...

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    18

    Switches

    Can any one give an example of a switch?

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    Code:
    int number;
    cin>>number;
    switch(number)
    {
          case 1:    DoSomething();
                          break;
    
          case 2:   DoSomethingElse();
    
          case 666: DoEndOfWorld();
                           break;
    
          default: cout<<"Not Valid";
    }
    if number is 1 the DoSomething will be called. if number is 2 then DoSomethingElse will be called followed by DoEndOfWorld. if number is 666 then DoEndOfWorld is called. If number is anything else "not valid" gets printed.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User The Junglist's Avatar
    Join Date
    Nov 2002
    Posts
    42
    I assume that you're talking about switch statements.
    Code:
    #include <iostream>
    
    using std::cout;
    using std::cin;
    
    int main()
    {
        int x;
    
        cout << "Enter a number from 1 - 5 : ";
        cin >> x;
    
        switch( x )
        {
              case 1:   cout << "\nYou are dumb!"; break;
              case 2:   cout << "\nYou are average!"; break;
              case 3:   cout << "\nYou are clever!"; break;
              case 4:   cout << "\nYou are very clever!"; break;
              case 5:   cout << "\nYou are a genius!"; break;
              default:  cout << "\nYou are really dumb!"; break;
        }
    
        return 0;
    }
    The keyword break must be included if you want to "break" out of the switch statement. If a number is entered that is not in the range 1-5, then the default statement is executed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. simple question regarding switches
    By ove256 in forum Networking/Device Communication
    Replies: 2
    Last Post: 10-24-2005, 12:01 AM
  2. toggle switches and LEDs
    By cprogrammer2003 in forum C Programming
    Replies: 11
    Last Post: 07-22-2003, 12:35 PM
  3. switches and breaks
    By volk in forum C Programming
    Replies: 11
    Last Post: 01-10-2003, 07:55 PM
  4. Command-Line Switches
    By liveapple2000 in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 04-14-2002, 03:13 AM
  5. Microswitch joysticks and arcade switches
    By Scourfish in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 09-30-2001, 07:50 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21