- •Table of Contents
- •Introduction
- •About This Here Dummies Approach
- •How to Work the Examples in This Book
- •Foolish Assumptions
- •Icons Used in This Book
- •Final Thots
- •The C Development Cycle
- •From Text File to Program
- •The source code (text file)
- •The compiler and the linker
- •Running the final result
- •Save It! Compile and Link It! Run It!
- •Reediting your source code file
- •Dealing with the Heartbreak of Errors
- •The autopsy
- •Repairing the malodorous program
- •Now try this error!
- •The Big Picture
- •Other C Language Components
- •Pop Quiz!
- •The Helpful RULES Program
- •The importance of being \n
- •Breaking up lines\ is easy to do
- •The reward
- •More on printf()
- •Printing funky text
- •Escape from printf()!
- •A bit of justification
- •Putting scanf together
- •The miracle of scanf()
- •Experimentation time!
- •Adding Comments
- •A big, hairy program with comments
- •Why are comments necessary?
- •Bizarr-o comments
- •C++ comments
- •Using Comments to Disable
- •The More I Want, the More I gets()
- •Another completely rude program example
- •And now, the bad news about gets()
- •The Virtues of puts()
- •Another silly command-prompt program
- •puts() and gets() in action
- •More insults
- •puts() can print variables
- •The Ever-Changing Variable
- •Strings change
- •Running the KITTY
- •Hello, integer
- •Using an integer variable in the Methuselah program
- •Assigning values to numeric variables
- •Entering numeric values from the keyboard
- •The atoi() function
- •So how old is this Methuselah guy, anyway?
- •Basic mathematical symbols
- •How much longer do you have to live to break the Methuselah record?
- •The direct result
- •Variable names verboten and not
- •Presetting variable values
- •The old random-sampler variable program
- •Maybe you want to chance two pints?
- •Multiple declarations
- •Constants and Variables
- •Dreaming up and defining constants
- •The handy shortcut
- •The #define directive
- •Real, live constant variables
- •Numbers in C
- •Why use integers? Why not just make every number floating-point?
- •Integer types (short, long, wide, fat, and so on)
- •How to Make a Number Float
- •The E notation stuff
- •Single-character variables
- •Char in action
- •Stuffing characters into character variables
- •Reading and Writing Single Characters
- •The getchar() function
- •The putchar() function
- •Character Variables As Values
- •Unhappily incrementing your weight
- •Bonus program! (One that may even have a purpose in life)
- •The Sacred Order of Precedence
- •A problem from the pages of the dentistry final exam
- •The confounding magic-pellets problem
- •Using parentheses to mess up the order of precedence
- •The computer-genie program example
- •The if keyword, up close and impersonal
- •A question of formatting the if statement
- •The final solution to the income-tax problem
- •Covering all the possibilities with else
- •The if format with else
- •The strange case of else-if and even more decisions
- •Bonus program! The really, really smart genie
- •The World of if without Values
- •The problem with getchar()
- •Meanwhile, back to the GREATER problem
- •Another, bolder example
- •Exposing Flaws in logic
- •A solution (but not the best one)
- •A better solution, using logic
- •A logical AND program for you
- •For Going Loopy
- •For doing things over and over, use the for keyword
- •Having fun whilst counting to 100
- •Beware of infinite loops!
- •Breaking out of a loop
- •The break keyword
- •The Art of Incrementation
- •O, to count backward
- •How counting backward fits into the for loop
- •More Incrementation Madness
- •Leaping loops!
- •Counting to 1,000 by fives
- •Cryptic C operator symbols, Volume III: The madness continues
- •The answers
- •The Lowdown on while Loops
- •Whiling away the hours
- •Deciding between a while loop and a for loop
- •Replacing those unsightly for(;;) loops with elegant while loops
- •C from the inside out
- •The Down-Low on Upside-Down do-while Loops
- •The devil made me do-while it!
- •do-while details
- •The always kosher number-checking do-while loop
- •Break the Brave and Continue the Fool
- •The continue keyword
- •The Sneaky switch-case Loops
- •The switch-case Solution to the LOBBY Program
- •The Old switch-case Trick
- •The Special Relationship between while and switch-case
- •A potentially redundant program in need of a function
- •The noble jerk() function
- •Prototyping Your Functions
- •Prototypical prototyping problems
- •A sneaky way to avoid prototyping problems
- •The Tao of Functions
- •The function format
- •How to name your functions
- •Adding some important tension
- •Making a global variable
- •An example of a global variable in a real, live program
- •Marching a Value Off to a Function
- •How to send a value to a function
- •Avoiding variable confusion (must reading)
- •Functions That Return Stuff
- •Something for your troubles
- •Finally, the computer tells you how smart it thinks you are
- •Return to sender with the return keyword
- •Now you can understand the main() function
- •Give that human a bonus!
- •Writing your own dot-H file
- •A final warning about header files
- •What the #defines Are Up To
- •Avoiding the Topic of Macros
- •A Quick Review of printf()
- •The printf() Escape Sequences
- •The printf() escape-sequence testing program deluxe
- •Putting PRINTFUN to the test
- •The Complex printf() Format
- •The printf() Conversion Characters
- •More on Math
- •Taking your math problems to a higher power
- •Putting pow() into use
- •Rooting out the root
- •Strange Math? You Got It!
- •Something Really Odd to End Your Day
- •The perils of using a++
- •Oh, and the same thing applies to a --
- •Reflections on the strange ++a phenomenon
- •On Being Random
- •Using the rand() function
- •Planting a random-number seed
- •Randoming up the RANDOM program
- •Streamlining the randomizer
- •Arrays
- •Strings
- •Structures
- •Pointers
- •Linked Lists
- •Binary Operators
- •Interacting with the Command Line
- •Disk Access
- •Interacting with the Operating System
- •Building Big Programs
- •Use the Command-Line History
- •Use a Context-Colored Text Editor
- •Carefully Name Your Variables
- •Breaking Out of a Loop
- •Work on One Thing at a Time
- •Break Up Your Code
- •Simplify
- •Talk through the Program
- •Set Breakpoints
- •Monitor Your Variables
- •Document Your Work
- •Use Debugging Tools
- •Use a C Optimizer
- •Read More Books!
- •Setting Things Up
- •The C language compiler
- •The place to put your stuff
- •Making Programs
- •Finding your learn directory or folder
- •Running an editor
- •Compiling and linking
- •Index
Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 243
You’re changing all the if statements into a switch-case thing. Be careful what you type. When you’re done, double-check Lines 19 through 37 in the source code to make sure that you got it right. (The first few lines of the pro gram don’t change.)
Compile. Fix any errors or typos. Note that those are colons — not semicolons — on the case lines. The character constants are enclosed in single quotes. The word default also ends in a colon.
Run. You should see no difference in the output. Internally, however, you have converted an ugly string of if-else statements into an elegant decisionmaking structure: the switch-case loop (or “structure thing”).
Detailed information on what happens in a switch-case loop is covered in the next section.
The switch command in Line 19 takes the single character typed at the keyboard (from Line 18) and tells the various case statements in its curly braces to find a match.
Each of the case statements (Lines 21, 24, 27, and 30) compares its char acter constant with the value of variable c. If there’s a match, the state ments belonging to that case are executed.
The break in each case statement tells the compiler that the switchcase thing is done and to skip the rest of the statements.
If the break is missing, execution falls through to the next group of case statements, which are then executed, no matter what. Watch out for that! Missing breaks are the bane of switch-case loops.
The final item in the switch-case thing is default. It’s the option that gets executed if no match occurs.
The Old switch-case Trick
This is one booger of a command to try to become comfy with. Although switch-case things are important, they contain lots of programming finesse that many beginners stumble over. My advice is to work through the programs in this chapter to get a feel for things and then check mark bullets in this section for review purposes or to figure out what went wrong when things don’t work.
The switch keyword is used to give your programs an easy way to make multiple-choice guesses. It should replace any long repetition of if-else statements you’re using to make a series of comparisons.
244 Part III: Giving Your Programs the Ability to Run Amok
Using switch involves creating a complex structure that includes the case, break, and default keywords. Here’s how it may look:
switch(choice)
{
case item1:
statement(s); break;
case item2:
case item3:
statement(s); break;
default:
statement(s);
}
choice must be a variable. It can be a key typed at the keyboard, a value returned from the mouse or joystick, or some other interesting number or character the program has to evaluate.
After the case keyword come various items; item1, item2, item3, and so on are the various items that choice can be. Each one is a constant, either a char acter or a value; they cannot be variables. The case line ends in a colon, not in a semicolon.
Belonging to each case item are one or more statements. The program exe cutes these statements when item matches the choice that switch is making — like an if statement match. The statements are not enclosed in curly braces. The statements are also optional. (More on that in a second.)
The last statement in a group of case statements is typically a break com mand. Without the break there, the program keeps working its way through the next case statement.
The last item in the switch structure is default. It contains the statements to be executed when no match occurs — like the final else in an if-else structure. The default statements are executed no matter what (unless you break out of the structure earlier).
The most important thing to remember about switch-case is that the pro gram always walks through the entire thing unless you put a break in there when you want it to stop. For example, consider this program snippet:
switch(key)
{
case ‘A’:
printf(“The A key.\n”); break;
Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 245
case ‘B’:
printf(“The B key.\n”); break;
case ‘C’: case ‘D’:
printf(“The C or D keys.\n”); break;
default:
printf(“I don’t know that key.\n”);
}
Suppose that key is a single-character variable containing a character that was just typed at the keyboard. Here are three examples of how it would work:
Example 1: Suppose that the key variable contains the letter A. The program works:
switch(key)
Pick a key! So, key equals big A. Mosey on down the case list:
case ‘A’:
Yup, we have a match. The value of key equals the constant, big A. Execute those statements:
printf(“The A key.\n”);
Message printed. Then:
break;
Bail out of the switch-case thing. I’m done.
If you didn’t bail out at this point, the rest of the statements in the switchcase structure would be executed no matter what.
Example 2: Suppose that a user presses the C key. Here’s how it works:
switch(key)
key is a C. It’s time to check the case statements for a match:
case ‘A’:
246 Part III: Giving Your Programs the Ability to Run Amok
Nope! Skip to the next case:
case ‘B’:
Nope! Skip to the next case:
case ‘C’:
Yup! There’s a match. The value of key equals the character constant ‘C’ right here. What’s next?
case ‘D’:
The computer just goes ho-hum. There’s no match, but it’s still waiting for instructions because it matched the case ‘C’. Because the statements after case ‘D’ are the first that it finds, it executes those:
printf(“The C or D keys.\n”);
Message printed. Then:
break;
The rest of the switch-case structure is skipped.
Example 3: This time, the character X is entered at the keyboard. Here’s how the switch-case thing works:
switch(key)
key is an X. The computer wends its way through the case statements for a match:
case ‘A’:
Nope! Skip to the next case:
case ‘B’:
Nope! Skip to the next case:
case ‘C’:
Nope! Skip to the next case:
case ‘D’:
Chapter 19: Switch Case, or, From ‘C’ to Shining ‘c’ 247
Nope! All the cases are done. What’s left is the default, which supposedly handles everything else — including the X:
default:
and the only statement:
printf(“I don’t know that key.\n”);
The switch-case structure is done.
The thing in switch’s parentheses (choice) must work out to either a character value or an integer value. Most programmers put a character or integer variable there. You can also put a C language statement or function in the parentheses, as long as it works out to a character value or an integer value when it’s done.
The case line ends with a colon, not a semicolon. The statements belonging to case aren’t enclosed in curly braces.
The last statement belonging to a group of case statements is usually break. This statement tells the computer to skip over the rest of the switch structure and keep running the program.
If you forget the break, the rest of the switch structure keeps running. That may not be what you want.
The computer matches each item in the case statement with the choice that switch is making. If there’s a match, the statements belonging to that case are executed; otherwise, they’re skipped.
It’s possible for a case to lack any statements. In that case, a match simply “falls through” to the next case statement.
The keyword case must be followed by a constant value — either a number or a character. For example:
case 56: /* item 56 chosen */
or
case ‘L’: |
/* L key pressed */ |
You cannot stick a variable there. It just doesn’t work. You may want to. You may even e-mail me, asking whether you can, but you can’t. Give up now.
Most C manuals refer to the command as switch, and case is just another keyword. I use switch-case as a unit because it helps me remember that the second word is case and not something else.
You don’t need a default to end the structure. If you leave it off and none of the case’s items matches, nothing happens.