Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 8: Charting Unknown Cs with Variables 101

The integer variables are declared on one line, and the floating-point (non­ integer) variables on another.

Keep variables that are defined with a value on a line by themselves. To wit:

int first=1;

int the_rest;

Constants and Variables

In addition to the variable, the C language has something called a constant.

It’s used like a variable, though its value never changes.

Suppose that one day someone dupes you into writing a trigonometry pro­ gram. In this type of program, you have to use the dreaded value π (pi). That’s equal to 3.1415926 (and on and on). Because it never changes, you can create a constant named pi that is equal to that value.

Another example of a constant is a quoted string of text:

printf(“%s”,”This is a string of text”);

The text “This is a string of text” is a constant used with this printf() function. A variable can go there, though a string constant — a literal, quoted string — is used instead.

A constant is used just like a variable, though its value never changes.

A numeric constant is a number value, like π, that remains the same throughout your program.

π is pronounced “pie.” It’s the Greek letter p. We pronounce the English letter p as “pee.”

A string constant is a bit of text that never changes, though that’s really true of most text in a C language program. This chapter, therefore, con­ centrates primarily on numeric constants.

Dreaming up and defining constants

All this constant nonsense can seem silly. Then one day, you’re faced with a program like SPEED.C — except that the program is much longer — and you truly come to realize the value of a C language constant and the nifty #define directive you read about later in this chapter:

102 Part II: Run and Scream from Variables and Math

#include <stdio.h>

int main()

{

printf(“Now, the speed limit here is %i.\n”,55); printf(“But I clocked you doin’ %i.\n”,55+15); printf(“Didn’t you see that %i MPH sign?\n”,55); return(0);

}

Start over with a new slate in your editor. Carefully type the preceding source code. There’s nothing new or repulsive in it. Save the file to disk as SPEED.C.

Compile it! Fix it (if you have to)! Run it!

The output is pretty plain; something like this example is displayed:

Now, the speed limit here is 55.

But I clocked you doin’ 70.

Didn’t you see that 55 MPH sign?

Eh? No big deal.

But what if the speed limit were really 45? That would mean that you would have to edit the program and replace 55 with 45 all over. Better still, what if the program were 800 lines long and you had to do that? Not only that, but what if you had to change several other instances in which constants were used, and using your editor to hunt down each one and replace it properly would take months or years? Fortunately, the C language has a handy way around this dilemma.

You can easily argue that this isn’t a problem. After all, most editors have a search-and-replace command. Unfortunately, searching and replacing numbers in a computer program is a dangerous thing to do! Suppose that the number is 1. Searching and replacing it would change other values as well: 100, 512, 3.141 — all those would be goofed up by a search-and- replace.

For all you Mensa people out there, it’s true that the nature of the pro­ gram changes if the speed limit is lowered to 45. After all, was the scofflaw doing 70 or 60? To me, it doesn’t matter. If you’re wasting your excess IQ points on the problem, you can remedy it on your own.

The handy shortcut

The idea in this section is to come up with a handy shortcut for using number constants in C. I give you two solutions.

Chapter 8: Charting Unknown Cs with Variables 103

The first solution is to use a variable to hold the constant value:

int speed=55;

This line works because the compiler sticks the value 55 into the speed inte­ ger variable, and you can then use speed rather than 55 all over your program. To change the speed, you have to make only one edit:

int speed=45;

Although this line works, it’s silly because a variable is designed to hold a value that changes. The compiler goes to all that work, fluffing up the pillows and making things comfy for the variable, and then you misuse it as a con­ stant. No, the true solution is to define the constant value as a symbolic con­ stant. It’s really cinchy, as the updated SPEED.C program shows:

#include <stdio.h>

#define SPEED 55

int main()

{

printf(“Now, the speed limit here is %i.\n”,SPEED); printf(“But I clocked you doin’ %i.\n”,SPEED+15); printf(“Didn’t you see that %i MPH sign?\n”,SPEED); return(0);

}

Several changes are made here:

The program’s new, third line is another one of those doohickeys that begins with a pound sign (#). This one, #define, sets up a numeric con­ stant that can be used throughout the program:

#define SPEED 55

As with the #include thing, a semicolon doesn’t end the line. In fact, two big boo-boos with #define are using an equal sign and ending the line with a semicolon. The compiler will surely hurl error-message chunks your way if you do that.

The shortcut word SPEED is then used in the program’s three printf() statements to represent the value 55. There, it appears just like a number or variable in the printf statement.

Secretly, what happens is that the compiler sees the #define thing and all by itself does a search-and-replace. When the program is glued together, the value 55 is stuck into the printf() statements. The advantage is that you can easily update the constant values by simply editing the #define directive.

104 Part II: Run and Scream from Variables and Math

Carefully edit your SPEED.C source code so that it matches what you see listed here. Save the file to disk again and then recompile. It has the same output because your only change was to make the value 55 a real, live con­ stant rather than a value inside the program.

Again, the key is that it takes only one, quick edit to change the speed limit. If you edit Line 3 to read

#define SPEED 45

you have effectively changed the constant value 45 in three other places in the program. This change saves some time for the SPEED.C program — but it saves you even more time for longer, more complex programs that also use constant values.

Symbolic constant is C technospeak for a constant value created by the #define directive.

The #define directive

The #define construction (which is its official name, though I prefer to call it a directive) is used to set up what the C lords call a symbolic constant — a shortcut name for a value that appears over and over in your source code. Here’s the format:

#define SHORTCUT value

SHORTCUT is the name of the constant you’re defining. It’s traditional to name it like a variable and use ALL CAPS (no spaces).

value is the value the SHORTCUT takes on. It’s replaced by that value globally throughout the rest of your source code file. The value can be a number, equa­ tion, symbol, or string.

No semicolon is at the end of the line, but notice that the line absolutely must begin with a pound sign. This line appears at the beginning of your source code, before the main() function.

You should also tack a comment to the end of the #define line to remind you of what the value represents, as in this example:

#define SPEED 55 /* the speed limit */

Here, SPEED is defined to be the value 55. You can then use SPEED anywhere else in your program to represent 55.

Chapter 8: Charting Unknown Cs with Variables 105

A string constant can be created in the same way, though it’s not as popular:

#define GIRLFRIEND “Brenda” /* This week’s babe */

The only difference is that the string is enclosed in double quotes, which is a traditional C-string thing.

The shortcut word is usually written in ALL CAPS so as not to confuse it with a variable name. Other than that, the rules that apply to variable names typically apply to the shortcut words. Keep ’em short and simple is my recommendation.

You have to keep track of which types of constants you have defined and then use them accordingly, as shown in this example:

printf(“The speed limit is %i.\n”,SPEED);

And in this one: puts(GIRLFRIEND);

These lines may look strange, but they’re legit because the compiler knows what SPEED and GIRLFRIEND are shortcuts for.

No equal sign appears after the shortcut word!

The line doesn’t end with a semicolon (it’s not a C language statement)!

You can also use escape-sequence, backslash-character things in a defined string constant.

String constants that are set up with #define are rare. Only if the string appears many times over and over in your program is it necessary to make it a constant. Otherwise, most programs use printf() or puts() to display text on the screen.

You can also use math and other strangeness in a defined numeric con­ stant. This book doesn’t go into that subject, but something as obnox­ ious as the following line is entirely possible:

#define SIZE 40*35

Here, the shortcut word SIZE is set up to be equal to 40*35, whatever that figures out to be.

Using the #define thing isn’t required, and you’re not penalized if you don’t use it. Sure, you can stick the numbers in there directly. And,

you can use variables to hold your constants. I won’t pout about it. You won’t go to C prison.