Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes between Version 1 and Version 2 of SwitchCaseExample

Show
Ignore:
Author:
jcc7 (IP: 68.97.93.182)
Timestamp:
11/18/06 22:59:34 (17 years ago)
Comment:

more info

Legend:

Unmodified
Added
Removed
Modified
  • SwitchCaseExample

    v1 v2  
    1 = Switch-Case Construct = 
     1= The `switch-case` Construct = 
    22 
    33''Part of'' SwitchCaseCategory 
    44 
    5 == Description == 
     5== Overview == 
    66 
    77The switch-case construct can be a good way to replace a complicated series of if/else if/else if/else. 
    88 
    9 == Example in D == 
     9 
     10== How is `switch-case` useful? == 
     11 
     12Let's say you write a program that has a menu with a bunch of mutually exclusive options. 
     13 
     14{{{ 
     15+---------+------+-------+------+ 
     16| File    | Edit | Tools | Help | 
     17+---------+------+-------+------+ 
     18| New     | 
     19| Open    | 
     20| Save    | 
     21| Print   | 
     22|---------+ 
     23| Exit    | 
     24+---------+ 
     25}}} 
     26 
     27This is just the kind of situation that lead to the creation of the switch-case construct: only one of these options can be clicked at any given time. You can't click "Open" and "Exit" at the same time. So let's just go down the list. Maybe "New" was clicked, so run subroutine `NewWasClicked()`. If "Open" was clicked, then run subroutine `OpenWasClicked()`. And so on down list. If "Exit" was clicked then just `PostQuitMessage(0)`. Finally the `default case` is there so that you can catch whatever might fall through the cracks. 
     28 
     29== Don't fall through (unless you want to) == 
     30 
     31D follows in the C/C++ tradition of "falling through" from the matched case to the cases below if there isn't a `break` statement. So unless you actually want all the code for the lower cases executed when the upper case is found, don't forget to include those `break`s.  
     32 
     33 
     34== Example in the D Programming Language == 
    1035 
    1136{{{ 
    4065}}} 
    4166 
    42 == Example in QuickBASIC == 
     67 
     68== Equivalent example in QuickBASIC == 
    4369{{{ 
    4470Dim i% 
    6086}}} 
    6187 
     88== Automatic Initialization == 
     89 
     90By the way, did you notice that `i` is never explicitly assigned a value? Since D uses "automatic initialization", the integer `i` is automatically assigned a default value of 0 as it is declared without specifying another value.  
     91 
     92 
    6293== Source == 
    6394 
    64 || Link || http://www.dsource.org/tutorials/index.php?show_example=23 || 
    65 || Posted by || jcc7 || 
    66 || Date/Time || Mon Mar 14, 2005 11:13 pm || 
     95|| Link || http://jcc_7.tripod.com/d/tutor/switch_case.html || 
     96|| Author || jcc7 || 
     97