Tcl - Switch Statement


Advertisements

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for unquoted switch statement in Tcl language is as follows −

switch switchingString matchString1 {body1} matchString2 {body2} ... matchStringn {bodyn}

The syntax for unquoted switch statement in Tcl language is as follows −

switch switchingString {
   matchString1 {
      body1
   }
   matchString2 {
      body2
   }
...
   matchStringn {
      bodyn
   }
}

The following rules apply to a switch statement −

  • The switchingString is used in a switch statement; used between the different blocks by comparing to the matchString.

  • You can have any number of matchString blocks within a switch.

  • A switch statement can have an optional default block, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.

Flow Diagram

Switch Statement

Example : Unquoted version

#!/usr/bin/tclsh

set grade C;

switch $grade  A { puts "Well done!" }  B { puts "Excellent!" }  C { puts "You passed!"  } F { puts "Better try again"   }   default {     puts "Invalid grade"   }
puts "Your grade is  $grade"

When the above code is compiled and executed, it produces the following result −

You passed!
Your grade is  C

Example : Quoted version

#!/usr/bin/tclsh

set grade B;

switch $grade {
   A {
      puts "Well done!"
   }
   B {
      puts "Excellent!"
   }

   C {
      puts "You passed!"
   }
   F {
      puts "Better try again"
   }
   default {
      puts "Invalid grade"
   }
}
puts "Your grade is  $grade"

When the above code is compiled and executed, it produces the following result −

Excellent!
Your grade is  B
tcl_decisions.htm
Advertisements