- •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
262 Part IV: C Level
If your source code has more than one function, the order in which they’re listed is important; you cannot use a function inside your source code unless it has first been declared or prototyped. If you have multiple functions in your source code, order them so that if one function calls another, that second function is listed first. Otherwise, you’re again saddled with prototyping errors.
The Tao of Functions
The C language allows you to put as many functions as you want in your source code. There really is no limit, though most programmers like to keep their source-code text files to a manageable size.
What is “manageable size”? It depends.
The larger the source code file, the longer it takes to compile.
Often times, it pays to break off functions into their own, separate source code files. It not only aids in debugging, but also makes recompiling larger files easier.
This book’s companion volume, C All-in-One Desk Reference For Dummies
(Wiley), contains information on creating and managing multimodule source code files.
The function format
Here’s the format of a typical function:
type name(stuff)
The type tells the compiler whether the function returns a value. If the type is void, the function doesn’t return any value. (It merely functs.) Otherwise, the type describes which type of value the function returns: char, int, float, or any of the standard C language variable declarations.
The name is the function’s name. It must be a unique name, not any keywords or names of other C language library functions, such as printf() or atio(). (For more on names, see the next section.)
Parentheses after the function’s name are required, as they are on all C language functions. The stuff inside the parentheses, if needed, defines whatever value (or values) are sent off to the function for evaluation, manipulation, or mutila tion. I cover this subject in Chapter 22. If there’s no stuff, the parentheses can be left empty or the word void can be used.
Chapter 20: Writing That First Function 263
The statements belonging to the function require curly braces to hug them close. Those statements are the instructions that carry out what the function is supposed to do. Therefore, the full format for the function is shown here:
type name(stuff)
{
statement(s);
/* more statements */
}
The function must be prototyped before it can be used. You do that by either listing the full function earlier than it’s first used in your source code or restat ing the function’s declaration at the start of your source code. For example:
type name(stuff);
This line, with a semicolon, is required in order to prototype the function used later on in the program. It’s just a copy-and-paste job, but the semicolon is required for the prototype. (If you forget, your compiler may ever so gently remind you with a barrage of error messages.)
Call it defining a function. Call it declaring a function. Call it doing a func tion. (The official term is defining a function.)
Naming rules for functions are covered in the next section.
Your C language library reference lists functions by using the preceding format. For example:
int atoi(const char *s);
This format explains the requirements and product of the atoi() func tion. Its type is an int, and its stuff is a character string, which is how you translate const char *s into English. (Also noted in the format is that the #include <stdlib.h> thing is required at the beginning of your source code when you use the atoi() function.)
How to name your functions
Functions are like your children, so, for heaven’s sake, don’t give them a dorky name! You’re free to give your functions just about any name, but keep in mind these notes:
Functions are named by using letters of the alphabet and numbers. Almost all compilers insist that your functions begin with a letter. Check your compiler’s documentation to see whether this issue is something your compiler is fussy about.
264 Part IV: C Level
Don’t use spaces in your function names. Instead, use underlines. For example, this isn’t a function name:
get the time()
But this is:
get_the_time()
You can use upperor lowercase when you’re naming your functions. A common tactic is to capitalize key letters in the function’s name:
getTheTime()
Most compilers are case sensitive, so if you use mixed case, be sure to remember how you type it. For example, if the function is named getTheTime and you type GetTheTime, you may get a linker error (the function was not found).
Keep your function names short and descriptive. A function named f() is permissible yet ambiguous — it’s like saying “Nothing” when someone asks you what you’re thinking.
Some compilers may forbid you to begin a function name with an under line. It sounds bizarre, I know, but the following may be verboten:
_whatever()
Avoid naming your functions the same as other C language functions or keywords. Be unique!
The function name main() is reserved for your program’s first function.
Chapter 21
Contending with Variables in Functions
In This Chapter
Naming variables within functions
Understanding local variables
Sharing one variable throughout a program
Using global variables
Each function you create can use its own, private set of variables. It’s a must. Just like the main() function, other functions require integer or character
variables that help the function do its job. A few quirks are involved with this arrangement, of course — a few head-scratchers that must be properly mulled over so that you can understand the enter function/variable gestalt.
This chapter introduces you to the strange concept of variables inside func tions. They’re different. They’re unique. Please avoid the desire to kill them.
Bombs Away with the
BOMBER Program!
The dropBomb() function in the BOMBER.C program uses its own, private vari able x in a for loop to simulate a bomb dropping. It could be an exciting ele ment of a computer game you may yearn to write, though you probably want to use sophisticated graphics rather than the sloppy console screen used here:
#include <stdio.h>
void dropBomb(void); |
/* prototype */ |
int main()
266 Part IV: C Level
{
printf(“Press Enter to drop the bomb:”); getchar();
dropBomb();
printf(“Yikes!\n”);
return(0);
}
void dropBomb()
{
int x;
for(x=20;x>1;x--)
{
puts(“ *”);
}
puts(“ BOOM!”);
}
Type the source code as listed here. In the puts() function in Line 20 are 10 spaces before the asterisk.) In Line 22 are 8 spaces before BOOM!.
Save the file to disk as BOMBER.C. Compile and run.
Press Enter to drop the bomb:
*
*
*
And so on. . . .
*
*
BOOM!
Yikes!
Yeah, it happens a little too fast to build up the nerve-tingling anticipation of a true video game, but the point here is not dropping bombs; rather, the vari able x is used in the dropBomb() function. It works just fine. Nothing quirky. Nothing new. That’s how variables are used in functions.
See how the dropBomb() function declares the variable x:
int x;
It works just like it does in the main() function: Declare the variables right up front. Refer to Chapter 8 for more information about declaring variables.
The dropBomb() function is a void because it doesn’t return any values. It has nothing to do with any values used inside the function.