random
random

Reputation: 1

How to use switch statement in c

How can I use switch statement in the following lines, as I don't want to make the if statement bulky.

if(uword1 == (65|69|73|76|78|79|82|83|84|85)) {
    total1++;
    printf("%i", total1);
}

Upvotes: 0

Views: 79

Answers (3)

Soumyajit Roy
Soumyajit Roy

Reputation: 1

For switch-case and if-statement both, the number of lines of code will be almost equal.

Here's how you do it in switch case:

switch(uword1)
    {
        case 65:
        case 69:
        case 73:
        case 76:
        case 78:
        case 79:
        case 82:
        case 83:
        case 84:
        case 85:
        total1++;
        printf("%i", total1);
        break;
        
        default:
        break;
    }

Here's the same code in if-statement:

if(
        (uword1==65) ||
        (uword1==69) ||
        (uword1==73) ||
        (uword1==76) ||
        (uword1==78) ||
        (uword1==79) ||
        (uword1==82) ||
        (uword1==83) ||
        (uword1==84) ||
        (uword1==85)
        )
    {
        total1++;
        printf("%i", total1);
    }

Upvotes: 0

nielsen
nielsen

Reputation: 7594

Whether to use switch-case or if is a matter of taste. An if-statement will not get more "bulky" than the switch-case:

   if( uword1 == 65 ||
       uword1 == 69 ||
       uword1 == 73 ||
       uword1 == 76 ||
       uword1 == 78 ||
       uword1 == 79 ||
       uword1 == 82 ||
       uword1 == 83 ||
       uword1 == 84 ||
       uword1 == 85
   )
   {
       total1++;
       printf("%i", total1);
   }

Upvotes: 0

navylover
navylover

Reputation: 13539

  switch (uword1) {
    case 65:
    case 69:
    case 73:
    case 76:
    case 78:
    case 79:
    case 82:
    case 83:
    case 84:
    case 85:
        total1++;
        printf("%i", total1);
        break;
    default:
        break;
    }

Upvotes: 3

Related Questions