Like Tree1Likes
  • 1 Post By grumpy

Help with switch case

This is a discussion on Help with switch case within the C++ Programming forums, part of the General Programming Boards category; Code: switch(c) case 'a': cout <<"hello"; case 'b': cout << "hello"; if there anyway I can shorten the code since ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    51

    Help with switch case

    Code:
    switch(c)
    
    case 'a':
    
    cout <<"hello";
    
    case 'b':
    
    cout << "hello";

    if there anyway I can shorten the code since both case a and b do the exact same thing?

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,659
    Switch cases fall through unless there is a break statement. For example,
    Code:
    switch(c)
    {
        case 'a':
        case 'b':
              cout <<"hello";
              break;
        case 'c':
              cout << "bye";
              break;
    }
    will print "hello" is c is a or b, and print "bye" if c is 'c'.

    You could also use an "if" statement.
    iMalc likes this.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 08-25-2008, 01:01 PM
  2. Switch and Case
    By ednnd in forum C Programming
    Replies: 12
    Last Post: 10-07-2005, 10:46 PM
  3. Switch case
    By DeepFyre in forum C++ Programming
    Replies: 3
    Last Post: 09-25-2004, 07:29 PM
  4. Switch Case
    By FromHolland in forum C++ Programming
    Replies: 7
    Last Post: 06-13-2003, 04:51 AM
  5. Switch Case vs if else
    By WebSnozz in forum C++ Programming
    Replies: 15
    Last Post: 01-28-2003, 09:47 AM

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