
- •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

282 Part IV: C Level
Another way to argue with a function
This book shows you the modern, convenient way of declaring variables (or arguments) shuf fled off to a function. To wit:
void jerk(int repeat, char c);
{
and so on. . . .
You can also use the original format:
void jerk(repeat, c) int repeat;
char c;
{
and so on...
This declaration does the same thing, but it’s a little more confusing because the variable name is introduced first and then the “what it is dec laration” comes on the following line (or lines). Otherwise, the two are the same.
My advice is to stick with the format used in this book and try not to be alarmed if you see the other format used. Older C references may use the second format, and certain fogey C pro grammers may adhere to it. Beware!
Functions That Return Stuff
For some functions to properly funct, they must return a value. You pass along your birthday, and the function magically tells you how old you are (and then the computer giggles at you). This process is known as returning a value, and a heck of a lot of functions do that.
Something for your troubles
To return a value, a function must obey these two rules:
Warning! Rules approaching.
The function has to be defined as a certain type (int, char, or float, for example — just like a variable). Use something other than void.
The function has to return a value.
The function type tells you what type of value it returns. For example:
int birthday(int date);
The function birthday() is defined on this line. It’s an integer function and returns an integer value. (It also requires an integer parameter, date, which it uses as input.)

Chapter 22: Functions That Actually Funct 283
The following function, nationalDebt(), returns the national debt of the United States as a double value:
double nationalDebt(void)
The void in parentheses means that the function doesn’t require any input. Likewise, when a function doesn’t produce any output, it’s defined as a void:
void USGovernment(float tax_dollars)
The USGovernment() function requires very large numbers as input, but pro duces nothing. Therefore, it’s a function of type void. It’s easy to remember.
Any value produced by a function is returned by using the return key word. Details appear later in this chapter.
Notice that C language functions, like atoi() or getchar() — functions that return values — are listed in your C language library reference by using the same format as described here:
int atoi(char *s)
char getchar(void)
This means that the atoi() function returns an integer value and that getchar() returns a single-character value.
Another reason functions should be prototyped: The compiler doublechecks to confirm that the function is returning the proper value and that other parts of the program use that int, float, or char value as defined.
You need a double-size variable to handle the national debt. The float variable, although it’s capable of handling a number in the trillions, is accurate to only 7 digits. The double is accurate to 15 digits. If the debt were calculated as a float, it would lose accuracy around the $100,000 mark (like they care about values that small!).
Although you can define a function as a type of void, you cannot declare a void variable. It just doesn’t work that way.
void functions don’t return values.
Functions can return only a single value. Unlike sending a value to a func tion, in which the function can receive any number of values, they can cough up only one thing in return. I know — it sounds like a gyp.
The preceding check mark is untrue. Functions can return several values. They do it through the miracle of pointers and structures, two advanced subjects touched on in this book’s companion, C All-in-One Desk Reference For Dummies (Wiley).

284 Part IV: C Level
Finally, the computer tells you how smart it thinks you are
The following program calculates your IQ. Supposedly. What’s more important is that it uses a function that has real meaning. If you have read the past few chapters, you have used the following set of C language statements to get input from the keyboard:
input=gets();
x=atoi(input);
The gets() function reads in text that’s typed at the keyboard, and atoi() translates it into an integer value. Well, ho-ho, the getval() function in the IQ.C program does that for you, returning the value happily to the main() function:
#include <stdio.h> #include <stdlib.h>
int getval(void);
int main()
{
int age,weight,area; float iq;
printf(“Program to calculate your IQ.\n”); printf(“Enter your age:”);
age=getval();
printf(“Enter your weight:”); weight=getval();
printf(“Enter the your area code:”);
area=getval();
iq=(age*weight)/area;
printf(“This computer estimates your IQ to be %f.\n”,iq); return(0);
}
int getval(void)
{
char input[20]; int x;
gets(input);
x=atoi(input);
return(x);
}

Chapter 22: Functions That Actually Funct 285
Type the source code for IQ.C into your editor. The new deal here is the getval() function, which returns a value by using the return keyword. (Does that look familiar? I tell you more in a second!)
Save the source code file to disk as IQ.C.
Compile. Run.
Here’s what the sample output may look like, using fictitious figures for myself:
Enter your age:33
Enter your weight:175
Enter your area code:208
The computer estimates your IQ to be 27.000000.
Of course. I knew my IQ was that high. I’m not boasting or anything. It’s only an estimate, after all.
By using this formula, only old, fat people living in low-numbered area codes can get into Mensa.
This program has some problems. For example, the IQ value that’s calcu lated should be a floating-point number, and it’s not (unless your age, weight, and area code are very special). This problem is fixed in the nearby sidebar, “Fixing IQ.C by using the old type-casting trick.”
Note how getval() is defined as an integer function. Inside getval(), an integer value is produced by the atoi() function. It’s saved in the x variable, which is then returned to the main function by using the return(x); statement. Everything is an integer, so the function is of that type as well.
In the main() function, getval() is used three times. The values it pro duces (what it functs) is saved in the age, weight, and height integer variables, respectively.
Yeah, you probably lied too when you entered your weight. Don’t! The more tumid you are, the smarter the program makes you.
Return to sender with the return keyword
Functions that return values need some type of mechanism to send those values back. Information just can’t fall off the edge, with the compiler assum ing that the last curly brace means “Hey, I must return the variable, uh, x. Yeah. That’s it. Send x back. Now I get it.”

286 Part IV: C Level
Fixing IQ.C by using the old type-casting trick
In the IQ.C source code, the computer estimates your IQ based on this formula:
iq=(age*weight)/area;
That is, your IQ is equal to your age multiplied by your weight, with that total divided by your area code. All those variables are integers, and, incidentally, it’s the exact formula used by my kids’ school district.
Alarm! Whenever you divide any two values, the result is probably a float. No, count on it being a float. That’s just the way math works. Decimals and fractions — it’s messy stuff.
To make this function work, the variable iq is declared as a float — right up at the begin ning of the source code, just as it should. But there’s a problem: The value calculated by the equation is still stuffed into an integer. (Eh?) Even though the calculated result probably has
a decimal part, all those variables are integers, and the result is an integer. (Hey, the compiler doesn’t assume anything, remember?)
To fix the problem, you must do something known as type casting, where you tell the compiler to temporarily forget what type of variable is there and instead assume that it’s something else.
Edit Line 19 in the IQ.C source code to read:
iq=(float)(age*weight)/area;
Insert the word float in parentheses right after the equal sign. Save the file back to disk. Compile and run. Notice that your IQ changes to a more floaty number in the output:
The computer estimates your IQ to be 27.764423.
Now the number is a true float.
No. To properly return a value, you need the proper return keyword.
The return keyword is used to send a value back from a function, to return a value from the function. Here’s the format:
return(something);
The something is a value that the function must return. What kind of value? It depends on the type of function. It must be an integer for int functions, a character for a char function, a string (which is tricky), a floater for a float function, and so on. And, you can specify either a variable name or a con stant value.
return(total);
The value of the variable total is returned from the function.
return(0);
The function returns a value of zero.