- •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 22
Functions That Actually Funct
In This Chapter
Sending a value to a function
Sending multiple values to a function
Using the return keyword
Understanding the main() function
Writing tighter code
Afunction is like a machine. Although the do-nothing void functions that you probably have read about in earlier chapters are still valid functions,
the real value in a function is having it do something. I mean, functions must chew on something and spit it out. Real meat-grinder stuff. Functions that funct.
This chapter explains how functions can be used to manipulate or produce information. It’s done by sending a value to a function or by having a function return a value. This chapter explains how all that kooky stuff works.
Marching a Value Off to a Function
Generally speaking, you can write four types of functions:
Functions that work all by themselves, not requiring any extra input:
These functions are described in previous chapters. Each one is a ho-hum function, but often necessary and every bit a function as a function can be.
Functions that take input and use it somehow: These functions are passed values, as either constants or variables, which they chew on and then do something useful based on the value received.
Functions that take input and produce output: These functions receive something and give you something back in kind (known as generating a value). For example, a function that computed your weight based on your shoe size would swallow your shoe size and cough up your weight. So to speak. Input and output.
276 Part IV: C Level
Functions that produce only output: These functions generate a value or string, returning it to the program — for example, a function that may tell you where the Enterprise is in the Klingon Empire. You call the whereEnt() function, and it returns some galactic coordinates.
Any function can fall into any category. It all depends on what you want the function to do. After you know that, you build the function accordingly.
How to send a value to a function
Sending a value to a function is as easy as heaving Grandma through a plate glass window. Just follow these steps:
1.Know what kind of value you’re going to send to the function.
It can be a constant value, a number or string, or it can be a C language variable. Either way, you must declare that value as the proper type so that the function knows exactly what type of value it’s receiving: int, char, or float, for example.
2.Declare the value as a variable in the function’s parentheses.
Suppose that your function eats an integer value. If so, you need to declare that value as a variable that the function will use. It works like declaring any variable in the C language, though the declaration is made inside the function’s parentheses following the function’s name:
void jerk(int repeat)
Don’t follow the variable declaration with a semicolon! In the preceding example, the integer variable repeat is declared, which means that the jerk() function requires an integer value. Internally, the function refers to the value by using the repeat variable.
3.Somehow use the value in your function.
The compiler doesn’t like it when you declare a variable and then that variable isn’t used. (It’s a waste of memory.) The error message reads something like jerk is passed a value that is not used or Parameter ‘repeat’ is never used in function jerk. It’s a warning error — and, heck, it may not even show up — but it’s a good point to make: Use your variables!
4.Properly prototype the function.
You must do this or else you get a host of warning errors. My advice: Select the line that starts your function; mark it as a block. Then, copy it to up above the main() function. After pasting it in, add a semicolon:
void jerk(int repeat);
No sweat.
Chapter 22: Functions That Actually Funct 277
5.Remember to send the proper values when you’re calling the function.
Because the function is required to eat values, you must send them along. No more empty parentheses! You must fill them, and fill them with the proper type of value: integer, character, floater — whatever. Only by doing that can the function properly do its thing.
The parameter is referred to as an argument. This term gives you a tiny taste of C’s combative nature.
The name you give the function’s parameter (its passed-along variable, argument, or whatever) is used when you’re defining and prototyping the function, and inside the function.
You can treat the function’s parameter as a local variable. Yeah, it’s defined in the prototype. Yeah, it appears on the first line. But, inside the func tion, it’s just a local variable.
By the way, the variable name used inside the function must match the variable name defined inside the function’s parentheses. More on this later.
Information on passing strings to functions is provided in my book C All- in-One Desk Reference For Dummies (Wiley).
Sending a value to a function or getting a value back isn’t the same as using a global variable. Although you can use global variables with a function, the values the function produces or generates don’t have to be global variables. (Refer to Chapter 21 for more information about global variables.)
An example (and it’s about time!)
Blindly type the following program, a modification of the BIGJERK.C cycle of programs you work with in Chapter 20:
#include <stdio.h>
void jerk(int repeat);
int main()
{
printf(“He calls me on the phone with nothing say\n”); printf(“Not once, or twice, but three times a day!\n”); jerk(1);
printf(“He insulted my wife, my cat, my mother\n”); printf(“He irritates and grates, like no other!\n”); jerk(2);
printf(“He chuckles it off, his big belly a-heavin’\n”); printf(“But he won’t be laughing when I get even!\n”); jerk(3);
278 Part IV: C Level
return(0);
}
/* The jerk() function repeats the refrain for the value of the repeat variable */
void jerk(int repeat)
{
int i;
for(i=0;i<repeat;i++) printf(“Bill is a jerk\n”);
}
You can edit this source code from the BIGJERK2.C file, but save this file to disk as BIGJERK4.C. It has some changes, mostly with the jerk() function and the statements that call that function. Don’t miss anything, or else you get some nasty error messages.
Compile and run.
The program’s output now looks something like this:
He calls me on the phone with nothing say
Not once, or twice, but three times a day!
Bill is a jerk
He insulted my wife, my cat, my mother
He irritates and grates, like no other!
Bill is a jerk
Bill is a jerk
He chuckles it off, his big belly a-heavin’
But he won’t be laughing when I get even!
Bill is a jerk
Bill is a jerk
Bill is a jerk
The jerk() function has done been modified! It can now display the litany’s refrain any old number of times. Amazing. And look what it can do for your poetry.
The details of how this program worked are hammered out in the rest of this chapter. The following check marks may clear up a few key issues.
Notice how the jerk() function has been redefined in the prototype:
void jerk(int repeat);
This line tells the compiler that the jerk() function is hungry for an integer value, which it calls repeat.
The new jerk() function repeats the phrase Bill is a jerk for what ever number you specify. For example: