- •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 29: Ten Ways to Solve Your Own Programming Problems 355
Simplify
Avoid the temptation to gang up several commands on one line until you’re certain that that part of your code works well. Do this for many reasons, but most importantly because it makes your code more readable. The more read able your code is, the easier it is for folks (including you) to find an error.
For example, rather than write this line:
while(toupper(getch())!=ZED)
write this one:
while( ch != ZED)
{
ch = getch();
ch = toupper(ch); /* and so on */
Yeah, it may take a few more lines, but if you get an error in one of those lines, you know exactly where to look. Before then, you could have had several potential trouble spots.
Also, the second example is more readable to other programmers.
Finally, when you’re certain that your code works, you can compact things on one line — if you want to. Remember that the object is to get the program to work, not to try to impress other programmers with your source code.
Talk through the Program
One of the best ways to find bugs almost instantly is to show your code to another programmer. But that other programmer isn’t familiar with what you’re doing. What you do is start “talking through” the logic of your code. You explain what does what and why you made the choices you did.
Suddenly, as you’re explaining what you did, you discover that one spot in your code that doesn’t match your intentions. You say, “A-ha!” The other programmer nods in agreement, and you’re on with your work.
This technique of talking through your program works whether or not another programmer is present.
356 Part V: The Part of Tens
Set Breakpoints
You know that the bug is in the windshield() function, but you don’t know where. Does the bug lurk at the beginning of your code? In the initialization routines? Just before the big math functions? Near the end? Where? Where? Where?
One way to find out is to put breakpoints into your program. At a certain spot, stick in a return() or exit() function, which immediately stops the program. That way, you can narrow down the pesky code. If the program stops per the breakpoint, the fault lies beyond that point in the program. If the program doesn’t stop with the breakpoint, the fault lies before it.
Monitor Your Variables
Sometimes, a program runs amok because the values that you suspected were in your variables just aren’t there. To confirm that the variables aren’t carrying something outrageous, occasionally toss in a printf() statement to display their values to the screen. Never mind if this technique screws up the display; the purpose is debugging.
For example, I had a program with a nasty endless loop in it. I couldn’t figure out for the life of me why it repeated and repeated. Talking through the source code did nothing. But after I stuck in a printf() statement that displayed the looping variable’s value, I noticed that it merrily skipped over the end-of- loop value and kept incrementing itself to infinity and beyond. I added a simple if statement to fix the problem, and the program ran just fine afterward.
Document Your Work
At university, they’re on you like gum on a theater floor about comments. Comment this! Comment that! I remember seeing classmates turn in projects that were three pages of greenbar paper in length, and half of that consisted of the dumb comments at the “top” of the program. Such nonsense impresses no one.
True, document your work. But documentation merely consists of notes to a future version of yourself. It’s a reminder to say “This is what I was thinking” or “Here is where my train of thought is going.”
You don’t have to document every little stupid part of the program. This comment is useless:
|
|
|
Chapter 29: Ten Ways to Solve Your Own Programming Problems 357 |
|
|
|
|
||
|
|
|
||
|
i++; |
/* add one to the value of i */ |
|
|
|
|
|
|
|
Here’s a better comment:
/* Remember that zero is the first item, so increment variable i here to account for that and not confuse the user. */
i++;
Comments can also tell a future version of yourself where to start working on the program if you come back to it later:
/* This is the payoff routine. In the future, it would be cool to add a sound effect here, say, coins in a hopper a la a slot machine. */
Comments can also be notes on what to fix, to remind you of what went wrong before and to give you tips on how to approach the problem:
/* I can’t get the dumb address to resolve here. The routine is supposed to work, but it keeps returning
a null value. Appendix C of the Davis book contains the original routine. */
Use Debugging Tools
If your compiler features a debugger, use it! Debuggers let you surgically view your program as it runs, monitoring variables and examining how the com puter literally steps through the code.
The problem with debuggers is that you usually need to compile a special version of the program, after it contains the debugging code. This makes the program huge and sluggish. If you use a debugger, remember to not use the debugger code when you compile your final program.
Use a C Optimizer
Many fun tools out there examine your code and make suggestions for opti mization. One common tool is lint. Other tools exist as well; any C program ming Web site lists the variety — and many of them are open source (thank you, open source community).
358 Part V: The Part of Tens
Just as a spell checker doesn’t make you a better writer, optimizers don’t make you a better programmer. But they can help hone your code so that it runs better.
Other programming tools are available as well. In fact, the whole Unix operating system is designed around programming. If you have time, consider looking into these tools: touch, make, and grep.
Read More Books!
One question I often get from programming acolytes via e-mail is “What book should I read next?” Well, obviously, the companion to this book, C All-in-One Desk Reference For Dummies, (Wiley) is an excellent choice. But the real answer is “Where do you want to go with your programming?”
If you want to program games, get books on game programming. You can find books for programming networks, programming the operating system, pro gramming graphics, and on and on. Some, you may have to find in university bookstores, but they exist.
As far as other programming languages are concerned, after reading through this book, you will know about 95 percent of the C++ program ming language. That would be a natural extension to this book. But also consider finding out how to use Perl, Java, Python, or any combination of those languages.
The PHP Web page creation language is also a good choice if you happen to be into the Web.
Above all, program. Practice. Devise new projects and work on ideas. Programming, to many folks, is like solving an enjoyable puzzle. Immerse yourself in it. Have fun!