Home > database >  Can I use a switch case on C with multiple values?
Can I use a switch case on C with multiple values?

Time:02-05

I'm working on that famous program that gives the date of tomorrow so I chose to use a switch to determine the months with 30 days in one case and the months with 31 days in another. When I write case 2: it works, but when I try to write case : 4,6,9,11 it shows me an error. How can I put multiple values in one case?

    switch (m) {
      case 2:
        do {
            printf("faire entrer le jour en chiffres ");
            scanf("%d", &j);
        } while (j > 29 || j < 1);
        if (j == 29) {
            j = 1;
            m = m  ;
            a = a;
        } else {
            j = j  ;
            m = m;
            a = a;
        };
        break;
      case (1||3||5||7||8||10||12) :
        do {
            printf("faire entrer le jour en chiffres \n");
            scanf("%d", &j);
        } while (j < 1 || j > 31);
        if (j == 31) {
            j = 1;
            m = m  ;
            a = a;
        } else {
           j  ;
           m = m;
           a = a;
        };
        break;
     case 4 6 9 11 :
        do {
            printf("faire entrer le jour par chifre \n");
            scanf("%d", &j);
        } while (j < 1 && j > 30);
        if (j == 30) {
            j = 1;
            m = m;
            a = a;
        } else {
            j = j  ;
            m = m;
            a = a;
        };
        break;
    }

CodePudding user response:

You need to use separate case labels like

case 1: case 3: case 5: case 7: case 8: case 10: case 12:
do {   
    //... 

Or the above line can be rewritten like

case 1: 
case 3: 
case 5: 
case 7: 
case 8: 
case 10: 
case 12:
do {   
    //... 

Pay attention to that there is no sense to place a null statement after the closing brace as you are doing as for example

}else{
  j=j  ;
  m=m;
  a=a;
} ; break
^^^^

It is better to write

}else{
  j=j  ;
  m=m;
  a=a;
}
break 

CodePudding user response:

@Vlad from Moscow well answers how to use a switch case with multiple values.

Yet given the repetitive nature of OP's code, consider a different solution than switch.

if (m < 1 || m > 12) {
  Handle_Error();
} else {
  static int eom[] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };      
  do {
    printf("faire entrer le jour par chifre \n");
    scanf("%d",&j);
  } while(j<1 || j>eom[m]);

  if(j == eom[m]) {
    j = 1;
    m  ;  // add code for December to adjust `a`
  } else {
    j  ;
  }
}

Of course we still need some more changes for February and leap years.

  • Related