Thread: could someone please explain switch cases?

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    12

    Question could someone please explain switch cases?

    Hi again everyone, I resently started to relearn C++, after
    fiddling with QBasic for awhile( I figured C++ would be too hard for a 14 year old...). Anyway, I'm having a little trouble with understading switch cases, and yes, I have read the tutorial serval times over...
    think before you code...

  2. #2
    Registered User codingmaster's Avatar
    Join Date
    Sep 2002
    Posts
    309
    switch is like if, but when u have to check for more possibilities, it would be hard, so u use switch

    syntax:

    switch(a)
    {
    a_1 : do_1
    a_2 : do_2
    a_3 : do_3
    ...
    a_n : do_n
    }

    example, a simple prog (u have to input a number between 1 and 5)

    Code:
    #include <stdio.h>
    
    int main()
    {
     int a;
     printf("Please input a number (1-5): ");
     scanf("%d", &a);
    
     switch(a){
         case 1: printf("one\n");
                  break;
         case 2: printf("two\n");
                  break;
         case 3: printf("three\n");
                  break;
         case 4: printf("four\n");
                  break;
         case 5: printf("five\n");
                  break;
     }
     return 0;
    }

    u use break to stop the prog going on checking the other cases in the switch



    another example:
    Code:
    #include <stdio.h>
    
    int main()
    {
     int a;
     printf("Please input a number (1-5): ");
     scanf("%d", &a);
    
     switch(a)
       {
         case 1: printf("one or...");
         case 2: printf("...two \n");
                 break;
         case 3: printf("three\n");
                  break;
         case 4: printf("four...");
         case 5: printf("...or five \n");
                  break;
       }
    return 0;
    }
    What happens, if someone inputs a number: n<1 or n>5

    here another example:

    Code:
    #include <stdio.h>
    
    int main()
    {
     int a,b;
     char opera;
     printf("Calculating \n");
     printf(" (number)(operator)(number) no spaces\n");
    
     printf("Input your numbers: ");
     scanf("%d%c%d", &a, &opera, &b);
    
     switch(opera){
         case '+': printf("%d + %d = %d \n",a ,b ,a+b);
                    break;
         case '-': printf("%d - %d = %d \n", a, b, a-b);
                    break;
         case '*': printf("%d * %d = %d \n", a, b, a*b);
                    break;
         case '/': printf("%d / %d = %d \n", a, b, a/b);
                    break;
         default: printf("%c : no operator\n", opera);
       }
     return 0;
    }

    When somebody inputs nothing or something wrong insteads of the operators (+,-,/,*) the prog uses the default case, and outputs an error.

    When ur c++ programmer, u can also use cout instead of printf and cin instead of scanf

  3. #3
    Registered User codingmaster's Avatar
    Join Date
    Sep 2002
    Posts
    309
    here the source (c++) using cout and cin
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
     int a;
     cout << "Please input a number (1-5): ";
     cin >> a;
    
     switch(a){
         case 1: cout << "one\n";
                  break;
         case 2: cout << "two\n";
                  break;
         case 3: cout << "three\n";
                  break;
         case 4: cout << "four\n";
                  break;
         case 5: cout << "five\n";
                  break;
     }
     return 0;
    }
    #######################

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
     int a;
     cout << "Please input a number (1-5): ";
     cin >> a;
    
     switch(a)
       {
         case 1: cout << "one or...";
         case 2: cout << "...two \n";
                 break;
         case 3: cout << "three\n";
                  break;
         case 4: cout << "four...";
         case 5: cout << "...or five \n";
                  break;
       }
    return 0;
    }
    ######################

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
     int a,b;
     char opera;
     cout << "Calculating \n";
     cout << " (number)(operator)(number) no spaces\n";
    
     cout << "Input your numbers: ";
     cin >> a >> opera >> b;
    
     switch(opera){
         case '+': cout << a << "+" << b << "=" << (a+b);
                    break;
         case '-': cout << a << "-" << b << "=" << (a-b);
                    break;
         case '*': cout << a << "*" << b << "=" << (a*b);
                    break;
         case '/': cout << a << "/" << b << "=" << (a/b);
                    break;
         default: cout << opera << ": no operator\n";
       }
     return 0;
    }

  4. #4
    Registered User codegirl's Avatar
    Join Date
    Jun 2003
    Posts
    76
    Would it help to see the equivalent if statements for a switch statement? For example, using codingmaster's code:

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
     int a,b;
     char opera;
     cout << "Calculating \n";
     cout << " (number)(operator)(number) no spaces\n";
    
     cout << "Input your numbers: ";
     cin >> a >> opera >> b;
    
     switch(opera){
         case '+': cout << a << "+" << b << "=" << (a+b);
                    break;
         case '-': cout << a << "-" << b << "=" << (a-b);
                    break;
         case '*': cout << a << "*" << b << "=" << (a*b);
                    break;
         case '/': cout << a << "/" << b << "=" << (a/b);
                    break;
         default: cout << opera << ": no operator\n";
       }
     return 0;
    }
    That is the same as:

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
     int a,b;
     char opera;
     cout << "Calculating \n";
     cout << " (number)(operator)(number) no spaces\n";
    
     cout << "Input your numbers: ";
     cin >> a >> opera >> b;
    
      if (opera == '+')
        cout << a << "+" << b << "=" << (a+b);
      else if (opera == '-')
        cout << a << "-" << b << "=" << (a-b);
      else if (opera == '*')
        cout << a << "*" << b << "=" << (a*b);
      else if (opera == '/')
        cout << a << "/" << b << "=" << (a/b);
      else
        cout << opera << ": no operator\n";
    
     return 0;
    }
    In this case, the switch statement may not look a whole lot easier to read or faster to type, but sometimes they can make your code much easier to read!

    And don't forget your "break" statements in the switch statements... without them, the rest of the switch statement will be executed, when you really only want one case to be executed. (Try removing the breaks and running it to see what happens.)
    My programs don't have bugs, they just develop random features.

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    as an interesting tidbit, I believe the target value of the a switch statement must resolve to an integer. That is in :

    switch(target)

    target must be evaluated as an int.

    That means basing the switch on something like a string, as below, won't work:

    Code:
    cout << "who is the most famous person of the twentieth century" << endl;
    char name[80];
    cin.getline(name, 79);
    
    switch(name)
    {
      case "Albert Einstein":
        cout << "Yup" << endl;
        break;
      case "Klem Kaddidlehopper":
        cout << "Not really" << endl;
        break;
      default:
        cout << "it's all a matter of opinion anyway" << endl;
        break;
    }
    The above code would need to be done with series of if/else statements, or create a menu to select from, or some other intermediary type code.

  6. #6
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    a switch statement is not exactly
    Code:
    if (x == 'c') do_something();
    Instead, it looks like this:
    Code:
    if (x == 'c') goto label_c;
    else if (x == 'd') goto label_d;
    else goto default;
    {
    label_c:
      do_something();
      break;
    label_d:
      something_Else();
      break;
    default:
      break;
    }
    This means that goto's are used, which can be a bad thing when declaring local variables.
    Code:
    label_a:
      int a;
    label_b:
      ++a;
    What would happen if there was a goto label_b command? The compiler would generate an error. A solution to this is to surround all switch case labels with brackets.
    Code:
    label_a:
    {
      int a;
    
    }
    label_b:
      ++a;  //this is still an error, but at least now it's obvious: it's out of scope

  7. #7
    Registered User codegirl's Avatar
    Join Date
    Jun 2003
    Posts
    76
    > a switch statement is not exactly
    > if (x == 'c') do_something();

    Well, it can be thought of as if statements if you use the break statements properly... but ygfperson is right, technically it's just labels and gotos, and in some instances it won't translate nicely to if statements! Local variables can also be a problem -- sometimes I will create a block in each case statement so I can safely declare local variables that will only exist in that case, but I'm not sure if that's the proper or best way to do it
    My programs don't have bugs, they just develop random features.

  8. #8
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Regardless of how you use them, inherently they jump around a lot which is not good. In assembly they would be quite a mess and they can get messy even in C but that is not to say that you should never use them. Just be aware of the overhead you might be adding to your code.

    Code:
    switch(x)
    {
      case 1:  DoSomething(); break;
      case 2:  DoSomethingElse();break;
    }
    A terrible example in assembly - not at all optimized so no complaints please - I just coded it off the top of my head.
    Code:
      mov       ax,[x]
    
    COMPARE:
      cmp       ax,1
      jz        FIRSTRESULT
      jmp       COMPAREAGAIN
    
    FIRSTRESULT:
      call      DoSomething
      jmp       ENDOFCOMPARE
    
    COMPAREAGAIN:
      mov       ax,[x]
      cmp       ax,2
      jz        SECONDRESULT
      jmp       ENDOFCOMPARE
    
    SECONDRESULT:
      call      DoSomethingElse
    
    ENDOFCOMPARE:
    Again, a crude example but I'm not programming a compiler here.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Error proofing my switch statement.
    By Shamino in forum C++ Programming
    Replies: 10
    Last Post: 01-04-2008, 04:38 PM
  2. Question about switch cases
    By cashmerelc in forum C Programming
    Replies: 5
    Last Post: 09-21-2007, 11:57 PM
  3. Switch Statements
    By lazyturtle in forum C++ Programming
    Replies: 12
    Last Post: 05-02-2007, 02:40 AM
  4. switch() inside while()
    By Bleech in forum C Programming
    Replies: 7
    Last Post: 04-23-2006, 02:34 AM
  5. nested switch issue
    By fsu_altek in forum C Programming
    Replies: 3
    Last Post: 02-15-2006, 10:29 PM