Forum Discussion

Nik's avatar
Nik
Icon for Cirrus rankCirrus
Feb 07, 2015

breaking out of a switch statement?

is it possible to break out of a switch statement like you would a loop? the break command doesn't seem to work.

my goal is to say.. if condition is met then use the default action, like this:

 

switch blah {
  "foo" {
    good condition { do good stuff }
    bad condition { skip to the end of the statement and execute default }
  default {
    tell the user he sucks
  }

 

4 Replies

  • tcl switch commands don't allow break or continue because those are specific to loops. There's also not a goto command, so what you'll wind up having to do if you need to do an inner conditional check is either repeat the default code in default and bad condition or else set a flag that gets checked outside the switch statement. Something like this...

     

    switch blah {
        "foo" {
            if {good condition} {
                 Do whatever
            } else if {bad condition {
                set badFlag 1
            }
        default {
            set badFlag 1
        }
    }
    
    if { [info exists badFlag] && $badFlag } {
         tell the user he sucks
    }
    

     

  • giltjr's avatar
    giltjr
    Icon for Nimbostratus rankNimbostratus

    Why have if's inside a switch or even use default. Why not:

     

       switch blah {
        "knownbadcond1" {set badFlag 1}
        "knownbadcond2" {set badFlag 1}
        "knownbadcond3" {set badFlag 1}
        "knowngoodcond1" {do good stuff1}   
        "knowngoodcond2" {do good stuff2}      
        "knowngoodcond3" {do good stuff3}  
        }    
       if { [info exists badFlag] && $badFlag } { tell the user he sucks }

     

  • giltjr's avatar
    giltjr
    Icon for Nimbostratus rankNimbostratus

    I guess it depends on how many conditionals there are also. If "foo" is the only conditional, then this would be simpler:

     

         if {"foo"} {
                 if {good condition} {
                     Do whatever
                } elseif {bad condition {
                    set badFlag 1
                }
         } 
    if { [info exists badFlag] && $badFlag } {  tell the user he sucks }