Tải bản đầy đủ (.pdf) (20 trang)

Living with Variability - Declaring Value-Type Variables

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (455.22 KB, 20 trang )

Part II
Basic C#
Programming
07_597043 pt02.qxd 9/20/05 1:45 PM Page 37
In this part . . .
T
he newest e-commerce, B2B, dot-com, whiz-bang
program uses the same basic building blocks as
the most simple temperature-conversion program. This
part presents the basics of creating variables, performing
arithmetic operations, and controlling the execution path
through a program. This fundamental C# is essential train-
ing, especially if you’re new to programming.
07_597043 pt02.qxd 9/20/05 1:45 PM Page 38
Chapter 3
Living with Variability —
Declaring Value-Type Variables
In This Chapter

Creating someplace to store things — the C# variable

Using integers

Handling fractional values

Declaring other types of variables

Handling numeric constants

Changing types
T


he most fundamental of all concepts in programming is that of the vari-
able. A C# variable is like a small box in which you can store things, partic-
ularly numbers, for later use. The term variable is borrowed from the world of
mathematics. For example, the mathematician may say the following:
n = 1
This statement means that from this point forward, the mathematician can
use the term n to mean 1 — that is, until the mathematician changes it to
something else (a number, an equation, a concept, and so on).
The meaning of the term variable doesn’t differ much in the programming
world. The C# programmer may say the following:
int n;
n = 1;
Those statements define a “thing”
n
and assign it the value 1. From that point
forward in the program, the variable
n
has the value 1, until the programmer
changes it to some other number.
Unfortunately for programmers, C# places several limitations on variables —
limitations that mathematicians don’t have to consider.
08_597043 ch03.qxd 9/20/05 1:47 PM Page 39
Declaring a Variable
When the mathematician says, “n is equal to 1,” that means the term n is
equivalent to 1 in some ethereal way. The mathematician is free to introduce
variables in a willy-nilly fashion. For example, the mathematician may say the
following:
x = y
2
+ 2y + y

if k = y + 1 then
x = k
2
Here, the mathematician has written a quadratic equation. Perhaps the vari-
ables x and y were previously defined somewhere. However, the mathemati-
cian then presents another variable k, sort of out of the blue. Here, k doesn’t
so much mean that k has the value of y plus 1 but that k takes the place of the
concept of y plus one — a sort of shorthand. Skim through any mathematics
book and you’ll see what I mean.
Programmers must be precise in their terminology. For example, a C# pro-
grammer may write the following code:
int n;
n = 1;
The first line means, “Carve off a small amount of storage in the computer’s
memory and assign it the name n.” This step is analogous to reserving one of
those storage lockers at the train station and slapping the label n on the side.
The second line says, “Store the value 1 in the variable n, thereby replacing
whatever that storage location already contains.” The train-locker equivalent
is, “Open the train locker, rip out whatever happens to be there, and shove a
1 in its place.”
The equals symbol (
=
) is called the assignment operator.
The mathematician says, “n equals 1.” The C# programmer says in a more
precise way, “Store the value 1 in the variable
n
.” (Think about the train
locker, and you see why that is preferable.) C# operators tell the computer
what you want to do. In other words, operators are verbs and not descrip-
tors. The assignment operator takes the value on its right and stores it in the

variable on the left.
What’s an int?
Mathematicians deal with concepts. They can make up variables any time
they want, and a single variable may have different meanings throughout the
40
Part II: Basic C# Programming
08_597043 ch03.qxd 9/20/05 1:47 PM Page 40
same equation. At best, mathematicians look at a variable as some amor-
phous value — at worst, some vague concept.
The mathematician may write the following:
n = 1;
n = 1.1;
n = House
n = “Texas is a dump”
Those lines equate the variable n with all sorts of things, and the mathemati-
cian thinks nothing of it. I don’t think about it much either except for that last
line. As the bumper stickers down here say, “Don’t mess with Texas.”
C# is not nearly that flexible. In C#, each variable has a fixed type. When you
allocate one of those train lockers, you have to pick the size you need. If you
picked an “integer locker,” you couldn’t turn around and hope to stuff the
entire state of Texas in it — maybe Rhode Island, but not Texas.
For the example in the preceding section of this chapter, you select a locker
that’s designed to handle an integer — C# calls it an
int
. Integers are the
counting numbers 1, 2, 3, and so on, plus 0 and the negative numbers –1, –2,
–3, and so on.
Before you can use a variable, you must declare it. After you declare a vari-
able as
int

, it can hold and regurgitate integer values, as the following exam-
ple demonstrates:
// declare a variable n
int n;
// declare an int variable m and initialize it
// with the value 2
int m = 2;
// assign the value stored in m to the variable n
n = m;
The first line after the comment is a declaration that creates a little storage
area,
n
, designed to hold an integer value. The initial value of
n
is not speci-
fied until it is assigned a value. The second declaration not only declares an
int
variable
m
but also initializes it with a value of 2.
The term initialize means to assign an initial value. To initialize a variable is
to assign it a value for the first time. You don’t know for sure what the value
of a variable is until it has been initialized.
The final statement in the program assigns the value stored in
m
, which is 2,
to the variable
n
. The variable
n

continues to contain the value 2 until it is
assigned a new value. (The variable
n
doesn’t lose its value when you assign
it to
m
.)
41
Chapter 3: Living with Variability — Declaring Value-Type Variables
08_597043 ch03.qxd 9/20/05 1:47 PM Page 41
Rules for declaring variables
You can initialize a variable as part of the declaration, as follows:
// declare another int variable and give it
// the initial value of 1
int o = 1;
This is equivalent to sticking a 1 into that
int
storage locker when you first
rent it, rather than opening the locker and stuffing in the value later.
Initialize a variable when you declare it. In most, but not all cases, C# initial-
izes the variable for you, but don’t rely on that fact.
You may declare variables anywhere (well, almost anywhere) within a pro-
gram. However, you may not use a variable until you declare it and set it to
some value. Thus, the following two assignments are not legal:
// the following is illegal because m is not assigned
// a value before it is used
int m;
n = m;
// the following is illegal because p has not been
// declared before it is used

p = 2;
int p;
Finally, you cannot declare the same variable twice.
Variations on a theme —
different types of int
Most simple variables are of type
int
. However, C# provides a number of
twists to the
int
variable type for special occasions.
All integer variable types are limited to whole numbers. The
int
type suffers
from other limitations as well. For example, an
int
variable can only store
values in the range from roughly –2 billion to 2 billion.
A distance of 2 billion inches is greater than the circumference of the Earth.
In case 2 billion isn’t quite large enough for you, C# provides an integer type
called
long
(short for
long int
) that can represent numbers as large as you
can imagine. The only problem with a
long
is that takes a larger train locker:
A
long

consumes 8 bytes (64 bits) — twice as much as a garden-variety
int
.
C# provides several other integer variable types, as shown in Table 3-1.
42
Part II: Basic C# Programming
08_597043 ch03.qxd 9/20/05 1:47 PM Page 42
Table 3-1 The Size and Range of C# Integer Types
Type Size Range of Values In Use
(bytes)
sbyte
1 –128 to 127
sbyte sb = 12;
byte
1 0 to 255
byte b = 12;
short
2 –32,768 to 32,767
short sn = 12345;
ushort
2 0 to 65,535
ushort usn = 62345;
int
4 –2 billion to 2 billion
int n = 1234567890;
uint
4 0 to 4 billion (exact
uint un = 3234567890U
values in the Cheat
Sheet inside the front

cover of this book)
long
8 –10
20
to 10
20

“a whole lot”
long l = 123456789012L
ulong
8 0 to 2 × 10
20
long ul = 123456789012UL
As I explain in the section “Declaring Numeric Constants,” later in this chap-
ter, fixed values such as 1 also have a type. By default, a simple constant such
as 1 is assumed to be an
int
. Constants other than an
int
must be marked
with their variable type. For example, 123U is an unsigned integer,
uint
.
Most integer variables are called signed, which means they can represent neg-
ative values. Unsigned integers can only represent positive values, but you
get twice the range in return. As you can see from Table 3-1, the names of
most unsigned integer types start with a
u
, while the signed types generally
don’t have a prefix.

Representing Fractions
Integers are great for most calculations. I made it into the 6th grade before I
ever found out that anything else existed. I still haven’t forgiven my 6th-grade
teacher for starting me down the slippery slope of fractions.
Many calculations involve fractions, which simple integers can’t accurately
represent. The common equation for converting from Fahrenheit to Celsius
temperatures demonstrates the problem, as follows:
// convert the temperature 41 degrees Fahrenheit
int nFahr = 41;
int nCelsius = (nFahr - 32) * (5 / 9)
43
Chapter 3: Living with Variability — Declaring Value-Type Variables
08_597043 ch03.qxd 9/20/05 1:47 PM Page 43
This equation works just fine for some values. For example, 41 degrees
Fahrenheit is 5 degrees Celsius. “Correct, Mr. Davis,” says my 6th-grade teacher.
Okay, try a different value: 100 degrees Fahrenheit. Working through the
equation, 100 – 32 is 68; 68 times
5

9
is 37. “No,” she says, “the answer is 37.78.”
Even that’s wrong, because it’s really 37.777 . . . with the 7s repeating forever,
but I’m not going to push the point.
An
int
can only represent integer numbers. The integer equivalent of 37.78 is
37. This lopping off of the fractional part of a number to get it to fit into an
integer variable is called integer truncation.
Truncation is not the same thing as rounding. Truncation lops off the frac-
tional part. Rounding picks the closest integer value. Thus, truncating 1.9

results in 1. Rounding 1.9 results in 2.
For temperatures, 37 may be good enough. It’s not like you wear short-sleeve
shirts at 37.7 degrees but pull on a sweater at 37 degrees. But integer trunca-
tion is unacceptable for many, if not most, applications.
Actually, the problem is much worse than that. An
int
can’t handle the ratio
5

9
either; it always yields the value 0. Consequently, the equation as written in
this example calculates
nCelsius
as 0 for all values of
nFahr
. Even I admit
that’s unacceptable.
This book’s CD includes an
int
-based temperature conversion program con-
tained in the
ConvertTemperatureWithRoundOff
directory. At this point,
you may not understand all the details, but you can see the conversion equa-
tions and execute the program
ConvertTemperatureWithRoundOff.exe
to
see the results.
Handling Floating Point Variables
The limitations of an

int
variable are unacceptable for some applications.
The range generally isn’t a problem — the double-zillion range of a 64-bit-long
integer should be enough for anyone. However, the fact that an
int
is limited
to whole numbers is a bit harder to swallow.
In some cases, you need numbers that can have a nonzero fractional part.
Mathematicians call these real numbers. Somehow that always seemed like a
ridiculous name for a number. Are integer numbers somehow unreal?
Notice that I said a real number can have a nonzero fractional part — that is,
1.5 is a real number, but so is 1.0. For example, 1.0 + 0.1 is 1.1. Just keep that
point in mind as you read the rest of this chapter.
44
Part II: Basic C# Programming
08_597043 ch03.qxd 9/20/05 1:47 PM Page 44

×