- •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 27
Ten More Things You Need to Know about the C Language
In This Chapter
Using arrays
Understanding strings
Dealing with structures
Growing frustrated over pointers
Messing with linked lists
Manipulating bits
Interacting with the command line
Doing disk access
Interacting with the operating system
Building big programs
Your C language journey is far from over. C has so much more ground to be covered that it just couldn’t all possibly fit into this one book, at least
not at the same easygoing pace.
To give you a hint of things to come, here are ten more important aspects of the C language — and programming in general — that you may want to con sider pursuing. (Note that these topics are all covered in this book’s compan ion volume, C All-in-One Desk Reference For Dummies, also published by Wiley.)
Arrays
An array is a multivariable. It allows you to store many different integers, floating-point values, characters, strings, or any variable type in a single unit. Suppose that the combination to the Big Safe at Fort Knox is
32, 17, 96
340 Part V: The Part of Tens
Those three numbers are integers, of course. But the three of them stored together form an array.
Arrays are declared just like other variables, though the variable name ends with a set of square brackets:
int combination[3];
In this example, the combination array is declared. It can hold three items, which is what the 3 in square brackets specifies.
Arrays can also be declared and assigned at the same time, as in
float temps[] = { 97.0, 98.2, 98.6, 99.1 };
This array is named temps and contains four floating-point values.
Each item inside the array can be referred to individually. The items are known as elements.
The first element in an array is numbered zero. This is important to remember. So element zero in the temps[] array is 97.0.
Values are assigned to arrays just as they are to regular variables. For example:
combination[0] = 32; combination[1] = 17; combination[2] = 96;
These three statements assign the values 32, 17, and 96 to the three ele ments in the combination[] array. (Note that the first element is zero.)
The only bummer about arrays in the C language is that their size is fixed. After you set, or dimension, an array to hold a specific number of elements, that number is fixed and cannot be changed, which will cause you endless frustration in the future. For now, consider yourself forewarned.
Strings
A string is nothing more than an array of characters. For example:
char myname[] = “Dan”;
This declaration creates a string variable named myname. The contents of that variable are Dan, or the letters D, a, and n. You can also write it in a more tra ditional array style:
char myname[] = { ‘D’, ‘a’, ‘n’ };
Chapter 27: Ten More Things You Need to Know about the C Language 341
Strings always end with the NULL character, ASCII code 0, which is also defined in STDIO.H as the word NULL or character code \0 (backslash zero). Here’s the long way to create the string myname:
myname[0] = ‘D’; myname[1] = ‘a’;
myname[2] = ‘n’; myname[3] = ‘\0’;
That final NULL character tells the compiler where the string ends. Remember that strings can contain characters, such as Enter and Tab. The C language uses character code 0, or NULL, to mark the end of text.
A string is nothing more than a character array.
All strings end with the NULL character.
This book shows you how to use scanf() and gets() to read in strings. And, you can use the %s placeholder in the printf() function to display string values.
Many, many functions in the C language manipulate strings.
One C language string function is strcmp(), which is used to compare strings. Remember that you cannot use == in an if statement to com pare strings, but you can use the strcmp() or similar functions.
Structures
The C language lets you combine variables into a single package called a structure. It’s similar to a record in a database in that the structure variable can be used to describe a number of different things all at once. It’s roughly the equivalent of a 3-by-5 card.
Structures are declared by using the struct keyword. It’s followed by the name of the structure and its contents:
struct sample
{
int a; char b;
}
This structure is named sample. It contains two variables: an integer named a and a character named b. Note that this command merely creates the structure — it doesn’t declare any variables. To do that, you need another line.
342 Part V: The Part of Tens
The following line declares a structure variable named s1. The structure it uses is of the type defined as sample:
struct sample s1;
Suppose that you’re writing a game and need some way to track the charac ters inside the game. Consider the following structure:
struct character
{
char[10] name; long score;
int strength; int x_pos; int y_pos;
}
This structure is named character. It contains variables that describe variable attributes of a character in the game: the character’s name, score, strength, and location on the game grid.
To define four characters used in the game, the following declarations are needed:
struct character g1; struct character g2;
struct character g3; struct character g4;
Or:
struct character g1, g2, g3, g4;
Items within the structure are referred to by using dot notation. Here’s how the name for character g1 are displayed:
printf(“Character 1 is %s\n”,g1.name);
Suppose that character g2 is decimated by a sword thrust:
g2.strength -= 10;
This statement subtracts 10 from the value of g2.strength, the strength integer in character g2’s structure.
Yes, structures are one way to do database work in the C language.
Obviously, there is quite a bit to this structure thing — much more than can be included in one section.