music |
OSdata.com |
case or switch
summary
This subchapter looks at case or switch.
free computer programming text book projecttable of contents
|
music |
OSdata.com |
This subchapter looks at case or switch.
free computer programming text book projecttable of contents
|
This subchapter is a stub section. It will be filled in with instructional material later. For now it serves the purpose of a place holder for the order of instruction.
Professors are invited to give feedback on both the proposed contents and the propsed order of this text book. Send commentary to Milo, PO Box 1361, Tustin, California, 92781, USA.
The other important decision structure is the CASE structure. Technically there is no need for a case structure, because all case structures can be written as a NESTED IF structure instead. Because readability is vital for successful long term maintenance of a prorgam, most modern langauges have a CASE structure (sometimes called a SWITCH structure).
In the basic CASE structure, we have one test and many possibilities. Each possibility is matched with a single sequential step, block of structured code, or subroutine. Normally only one of the choices is performed.
An example using a test for eye color:
CASE of eye color:
BLUE EYES: do the blue eyes block of code
BROWN EYES: do the brown eyes block of code
GREEN EYES: do the green eyes block of code
GRAY EYES: do the gray eyes block of code
OTHERWISE: do special exception block of code
Notice the existence of the OTHERWISE choice. This covers the exception cases where you had unexpected results.
Without getting into messy details now, note that some programming languages allow a fall through. For example, we might have wanted to do one extra step for blue eyes than we did for brown eyes, but that otherwise the two choices shared the same steps. We could have the one extra step occur in the blue eyes case, then fall through to the brown eyes and do all of the brown eyes steps. If the CASE determined that there were brown eyes, it would skip the extra blue eyes step and only do the brown eyes steps. I hope I didnt just confuse you. If that doesnt make sense, dont worry about it for now.
In the C programming language the reserved word for the case structure is switch.
switch (choice)
{
case 1:
case 2:
DoSomething(x);
break
case 3:
y = z + 5;
case 4:
DoSomethingElse(x,y);
a = b + c;
break
otherwise
z = a + x;
break
}
The switch key word is followed by and expression (usually just a single variable) inside parenthesis. The expression must evaluate to a result that is of type int (integer).
The options are placed inside a pair of curly braces. Each case is introduced by the reserved key word case and labelled by a constant expression. The constant expression must evaluate to either an integer number or a char (character). The expression is followed by a colon ( : ).
Each case constant-expression: must be followed by zero or more staatements.
If a case has no statements of its own, then execution falls through to the next item. This can be used to have more than one option have the same executable code. In the example, if the variable choice is equal to either 1 or 2, then the function DoSomething is performed with the variable x.
Execution continues in sequence until either a break key word is encountered or the end of the switch sttructure is found. In the example, if the variable choice is equal to 3, then the variable y will be set to Z + 5 and then the two statements of choice 4 will also be done.
The otherwise key word is used for every case that is not designated by the programmer (the default case).
The switch structure does not do any range checking. It is the responsibility of the programmer to do any range checking or other error checking.
The case statements can be in any order, although it is good programming practice to put them in an order that makes sense for the program (such as the ascending order of the example).
The break statement will move control outside a loop or switch statement.
Unlike most programming languages, Python doesnt have a caseor switch statement. Use if, elif, and else to create a series of cascading conditional statements.
Stanford CS Education Library This [the following section until marked as end of Stanford University items] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
The switch statement is a sort of specialized form of if used to efficiently separate different blocks of code based on the value of an integer. The switch expression is evaluated, and then the flow of control jumps to the matching const-expression case. The case expressions are typically int or char constants. The switch statement is probably the single most syntactically awkward and error-prone features of the C language.
switch (<expression>) {
case <const-expression-1>:
<statement>
break;
case <const-expression-2>:
<statement>
break;
case <const-expression-3> :// here we combine case 3 and 4
case <const-expression-4>:
<statement>
break;
default: // optional
<statement>
}
Each constant needs its own case keyword and a trailing colon (:). Once execution has jumped to a particular case, the program will keep running through all the cases from that point down -- this so called fall through operation is used in the above example so that expression-3 and expression-4 run the same statements. The explicit break statements are necessary to exit the switch. Omitting the break statements is a common error -- it compiles, but leads to inadvertent fall-through behavior.
Why does the switch statement fall-through behavior work the way it does? The best explanation I can think of is that originally C was developed for an audience of assembly language programmers. The assembly language programmers were used to the idea of a jump table with fall-through behavior, so thats the way C does it (its also relatively easy to implement it this way.) Unfortunately, the audience for C is now quite different, and the fall-through behavior is widely regarded as a terrible part of the language.
Stanford CS Education Library This [the above section] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
25 Case statements and if statements allow the selection of an enclosed sequence of statements based on the value of an expression or on the value of a condition. :Ada-Europes Ada Reference Manual: Introduction: Language Summary See legal information
28 Certain statements are associated with concurrent execution. One form of the select statement allows a selective wait for one of several alternative rendezvous. Other forms of the select statement allow conditional or timed entry calls and the asynchronous transfer of control in response to some triggering event. :Ada-Europes Ada Reference Manual: Introduction: Language Summary See legal information
Digital Equipment Corporations VAX Architecture Reference Manual gives the following example using the VAX PASCAL compiler (quoted under the fair use doctrine):
case i of
32: x := sin(x);
33: x := cos(x);
34: x := exp(x);
35: x := ln(x);
36, 37: x := arctanh(x);
otherwise x := reserved
end
casel i, #32, <#37-32>
1$: .word sin - 1$ ; Selector is 32.
.word cos - 1$ ; Selector is 33.
.word exp - 1$ ; Selector is 34.
.word ln - 1$ ; Selector is 35.
.word arctanh - 1$ ; Selector is 36.
.word arctanh - 1$ ; Selector is 37.
otherwise:
movl reserved, x ; Selector is less than.
; 32 or greater than 37
See also Program Control Instructions in Assembly Language
The following material is from the unclassified Computer Programming Manual for the JOVIAL (J73) Language, RADC-TR-81-143, Final Technical Report of June 1981.
1.1.6 Flow of Control
Here is an example of a case-statement:
CASE NUM;
BEGIN
(DEFAULT): TYPE=V(OUT'OF'RANGE);
(1,3,5,7,11,13,17,19): TYPE=V(PRIME);
(2,4,6,8:10,12,14:16,18,20 TYPE=V(NONPRIME);
This case statement sets TYPE to one of three status values,
depending on the value of the integer item NUM. If NUM is
outside of the range from 1 to 20, the status value is
"V(OUT'OF'RANGE)". If NUM is in the range and is prime, the
status value is "V(PRIME)". If NUM is in the range but not
prime, the status value is "V(NONPRIME)". Each time the
statement is eexecuted, the value of NUM is compared to the list
of values in parenthesis. If it matches one of them, then the
statement on that line is executed. The notation "8:10" means
"8,9,10".
The case-selector (NUM in the example just given) can be an
integer, bit, character, or status formula. It is not unusual for
a routine to be dominated by a single case-statement, and case-
statements are often nested within larger case-statements.
Chapter 1 Introduction, page 11
Commentary: Once again the example from the government manual highlights the need for rigiorous testing of your code. Two is a prime number and should be included in the list of primes rather than nonprimes. This also highlights the need for clear policy. While one technically meets the definition of a prime number (an integer whose only integer divisors are one and itself), it is generally excluded from prime numbers by policy. This policy has existed for at least two and half thousand years because it makes it much easier to derive important characteristics of prime numbers if you leave one out. Always test your code and always have clear policy decisions before,/i> coding.
Coding example: I am making heavily documented and explained open source code for a method to play music for free almost any song, no subscription fees, no download costs, no advertisements, all completely legal. This is done by building a front-end to YouTube (which checks the copyright permissions for you).
View music player in action: www.musicinpublic.com/.
Create your own copy from the original source code/ (presented for learning programming).
return to table of contents
free downloadable college text book
Because I no longer have the computer and software to make PDFs, the book is available as an HTML file, which you can convert into a PDF.
previous page | next page |
Tweets by @osdata |
free computer programming text book projectBuilding a free downloadable text book on computer programming for university, college, community college, and high school classes in computer programming. If you like the idea of this project, Supporting the entire project: If you have a business or organization that can support the entire cost of this project, please contact Pr Ntr Kmt (my church) free downloadable college text book on computer programming. |
This web site handcrafted on Macintosh computers using Tom Benders Tex-Edit Plus and served using FreeBSD .
UNIX used as a generic term unless specifically used as a trademark (such as in the phrase UNIX certified). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.
Names and logos of various OSs are trademarks of their respective owners.
Copyright © 2010, 2011, 2012 Milo
Created: October 17, 2012
Last Updated: March 15, 2011
return to table of contents
free downloadable college text book
previous page | next page |