Switch case with multiple values for the same case

16,571

Execution continues until it reaches a break;. Therefore, you can list cases one after the other to get the following code execute on either one of those cases.

String commentMark(int mark) {
    switch (mark) {
        case 0 : // Enter this block if mark == 0
            return "mark is 0" ;
        case 1:
        case 2:
        case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
            return "mark is either 1, 2 or 3" ;
        // etc.
        default :
            return "mark is not 0, 1, 2 or 3" ;
    }
}

The return statements above serve to get out of the function. If you do not want to return, you have to use break; after each block, of course. This code below is equivalent to the one above.

String commentMark(int mark) {
    String msg;
    switch (mark) {
        case 0 : // Enter this block if mark == 0
            msg = "mark is 0" ;
            break;
        case 1:
        case 2:
        case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
            msg = "mark is either 1, 2 or 3" ;
            break;
        // etc.
        default:
            msg = "mark is not 0, 1, 2 or 3" ;
            break; // this is a good habit, in case you change default to something else later.
    }
    return msg;
}

Share:
16,571

Related videos on Youtube

Mathieu
Author by

Mathieu

I am currently working at Octo as an Android Developer. During my studies in 42born2code school, I learned C language, especially UNIX system programmation. In my internship and apprenticeships, I have done Android Development. I have a tons of ideas of mobile apps, but not enough time to bring them to live for now. I am passionated about house automation, "bionic", robotic, drone... I want to learn about Lineage OS.

Updated on April 27, 2022

Comments

  • Mathieu
    Mathieu almost 2 years

    I would like to know the syntax to set a multiple case statement in a switch / case.
    For example :

    String commentMark(int mark) {
        switch (mark) {
            case 0 : // Enter this block if mark == 0
                return "Well that's bad" ;
            case 1, 2, 3 : // Enter this block if mark == 1 or mark == 2 or mark == 3
                return "Gods what happend" ;
            // etc.
            default :
                return "At least you tried" ;
        }
    }
    

    I cannot find the right syntax to set multiple case (the line case 1, 2, 3 :), is it even possible in Dart ?

    I did not found any informations on pub.dev documentation, neither on dart.dev.

    I tried :
    case 1, 2, 3
    case (1, 2, 3)
    case (1 ; 2 ; 3)
    case (1 : 2 : 3)
    case 1 : 3
    and more !

    • Vrushi Patel
      Vrushi Patel over 4 years
      try using 1...3