1585665292lesson 2 Variables
1585665292lesson 2 Variables
1585665292lesson 2 Variables
Computer programs usually work with different types of data and need a way to store the
values being used. These values can be numbers or characters. C has two ways of storing
number values — variables and constants — with many options for each. A variable is a data
storage location that has a value which can change during program execution. In contrast, a
constant has a fixed value that cannot change.
RAM
A computer uses random-access memory (RAM) to store information while it is operating.
RAM is located in integrated circuits, or chips, inside your computer. RAM is volatile, which
means it's erased and replaced with new information as often as needed. Being volatile also
means that RAM "remembers" only while the computer is turned on and loses its information
when you turn off the computer.
Amount of RAM
Each computer has a certain amount of RAM installed. The amount of RAM in a system is
usually specified in kilobytes (K), or megabytes (MB). One kilobyte of memory consists of
1,024 bytes. Thus, a system with 640K of memory actually has 640 times 1,024, or 655,360
bytes of RAM. One megabyte is 1,024 kilobytes.
Bytes
A byte is the fundamental unit of computer data storage. 0, "Odds and Ends," has more
information about bytes.
Table 2.1: Memory Space Required to Store Data
Data Bytes Required
The letter x 1
The number 100 2
The number 120.145 4
The phrase Teach Yourself C 17
One typewritten page 3,000 (approximately)
Addresses
The RAM in your computer is organized sequentially, one byte following another. Each byte
of memory has a unique address by which it is identified, an address that also distinguishes it
from all other bytes in memory. Addresses are assigned to memory locations in order, starting
at 0 and increasing to the system limit. For now, you needn't worry about addresses; it's all
handled automatically for you by the C compiler.
Usage of RAM
What is your computer's RAM used for? It has several uses, but only one, data storage, need
concern you as a programmer. Data means the information with which your C program
works. Whether your program is maintaining an address list, monitoring the stock market,
keeping a household budget, or tracking the price of hog bellies, the information (names,
stock prices, expense amounts, or hog futures) is kept in your computer's RAM while the
program is running.
Now that you understand a little about the nuts and bolts of memory storage, you can get
back to C programming and how C uses memory to store information.
2.2: Variables
Variables
A variable is a named data storage location in your computer's memory. By using a variable's
name in your program, you are, in effect, referring to the data stored there.
The following code contains some examples of legal and illegal C variable names:
percent /* legal */
y2x5__fg7h /* legal */
annual_profit /* legal */
_1990_tax /* legal but not advised */
savings#account /* illegal: contains illegal character # */
double /* illegal: is a C keyword */
9winter /* illegal: first character is a digit */
A program that calculates loan payments could store the value of the prime interest rate in a
variable named interest_rate. The variable name helps make its usage clear. You could as
well have created a variable named x or even johnny_carson; it doesn't matter to the C
compiler. The use of the variable, however, would not be nearly as clear to someone else
looking at the source code. Although it may take a little more time to type descriptive
variable names, the improvements in program clarity make it worthwhile.
Naming Conventions
Many naming conventions are used for variable names created from multiple words.
The Underscore
You've been shown one style: interest_rate. Using an underscore to separate words in a
variable name makes it easy to interpret.
Camel Notation
The second style is called camel notation. Instead of using spaces, the first letter of each word
is capitalized. Instead of interest_rate, the variable would be named InterestRate. Camel
notation is gaining popularity because it is easier to type a capital letter than an underscore.
This Course's Convention
We use the underscore in this course because it is easier for most people to read. You should
decide which style you wish to adopt.
DO understand the number of bytes that variable types take for your computer.
DON'T use a float or double variable if you are only storing integers. Although they will
work, using them is inefficient.
DON'T put negative numbers into variables with an unsigned type.
Small integer numbers (for example, 1, 199, –8) require less memory space for storage, and
mathematical operations (addition, multiplication, and so on) with such numbers can be
performed by your computer very quickly. In contrast, large integers and floating-point
values (123,000,000 or 0.000000871256, for example) require more storage space and more
time for mathematical operations.
Within each of these categories are two or more specific variable types. These are summarized here,
which also shows the amount of memory, in bytes, required to hold a single variable of each type
when you use a microcomputer with 16-bit architecture.
Approximate Range
Approximate range means the highest and lowest values a given variable can hold. (Space
limitations prohibit listing exact ranges for the values of these variables.)
Precision
Precision means the accuracy with which the variable is stored. (For example, if you evaluate
1/3, the answer is 0.33333 . . . with 3s going to infinity. A variable with a precision of 7
stores seven 3s.)
Description The output of Listing 3.1 tells you exactly how many bytes each
variable type on your computer takes. If you are using a 16-bit PC,
your numbers should match those in Table 2.2.
Lines 1 – 3 are comments about the name of the program and a brief
description.
Line 5 includes the standard input/output header file to help print the
information on the screen.
This is a simple program, in that it contains only a single function,
main() (lines 7 – 29).
Lines 8 – 27 are the bulk of the program. Each of these lines prints a
textual description with the size of each of the variable types, which is
done using the sizeof operator. 9, "Exploring the Function Library,"
covers the sizeof operator in detail.
Syntax
A variable declaration has the following form:
typename varname;
typename specifies the variable type and must be one of the keywords given in Table 2.2.
varname is the variable name, which must follow the rules mentioned earlier. You can
declare multiple variables of the same type on one line by separating the variable names with
commas.
int count, number, start;
/* three integer variables */
float percent, total;
/* two float variables */
Location
On 2, "Variable Scope," you will learn that the location of variable declarations in the source
code is important, because it affects the ways in which your program can use the variables.
For now, you can place all the variable declarations together just before the start of the
main() function.
2.3: Constants
Constants
Like a variable, a constant is a data storage location used by your program. Unlike a variable,
the value stored in a constant cannot be changed during program execution. C has two types
of constants, each with its own specific uses.
123.456
0.019
100.
Note that the third constant, 100., is written with a decimal point even though it is an integer
(that is, it has no fractional part). The decimal point causes the C compiler to treat the
constant as a double-precision value. Without the decimal point, it is treated as an integer
constant.
Integer Constants
A constant written without a decimal point is represented by the compiler as an integer number.
Integer constants can be written in three different notations:
A constant starting with any digit other than 0 is interpreted as a decimal integer
(that is, the standard base-10 number system). Decimal constants can contain the
digits 0 – 9 and a leading minus or plus sign. (Without a leading sign, a constant is
assumed to be positive.)
A constant starting with the digit 0 is interpreted as an octal integer (the base 8
number system). Octal constants can contain the digits 0 – 7 and a leading minus or
plus sign.
A constant starting with 0x or 0X is interpreted as a hexadecimal constant (the
base-16 number system). Hexadecimal constants can contain the digits 0 – 9, the
letters A – F, and a leading minus or plus sign.
Easier to Change
The second advantage of symbolic constants becomes apparent when you need to change a
constant. Continuing the preceding example, you may decide that for greater accuracy your
program needs to use a value of PI with more decimal places: 3.14159 rather than 3.14. If you
had used literal constants for PI, you would have to go through your source code and change
each occurrence of the value from 3.14 to 3.14159. With a symbolic constant, you would
need to make a change only in the place where the constant is defined.
Description of const
The second way to define a symbolic constant is with the const keyword. const is a modifier
that can be applied to any variable declaration. A variable declared to be const can't be
modified during program execution—only initialized at the time of declaration.
Examples of const
Here are some examples:
const int count = 100;
const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;
const affects all variables on the declaration line. In the last example, debt and tax_rate are
symbolic constants. If your program tries to modify a const variable, the compiler generates
an error message. For example,
const int count = 100;
count = 200; /* Does not compile! Cannot reassign or alter
the value of a constant. */
Description The program declares the two types of symbolic constants in lines 7
and 10. In line 7, a constant is being used to make the value 454 more
understandable. Because it uses GRAMS_PER_POUND, lines 25 – 26
are easy to understand.
Lines 12 and 13 declare the variables used in the program. Notice the
use of descriptive names such as weight_in_grams. By reading its
name, you see what this variable is used for.
Lines 25 – 27 calculate the user's weight in grams and his or her age in
the year 2000. Those statements and others are covered in detail
tomorrow.
To finish the program, lines 31 – 34 display the results for the user.
2.4: Q&A
Questions & Answers
Take a look at some questions that are frequently asked by programmers new to C.
Question 1
long int variables hold bigger numbers, so why not always use them instead of int variables?
Answer
A long int variable takes up more RAM than the smaller int. In smaller programs, this doesn't
pose a problem. As programs get bigger, however, try to be efficient with the memory you
use.
Question 2
What happens if I assign a number with a decimal to an integer?
Answer
You can assign a number with a decimal to an int variable. If you are using a constant
variable, your compiler probably will give you a warning. The value assigned will have the
decimal portion truncated. For example, if you assign 3.14 to an integer variable called pi, pi
will only contain 3. The .14 will be chopped off and thrown away.
Question 3
What happens if I put a number into a type that is not big enough to hold it?
Answer
Answer Many compilers will allow this without signaling any errors. The number is wrapped
to fit, however, and it isn't correct. For example, if you assign 2,147,483,648 to a four-byte
signed integer, the integer really contains the value -2,147,483,648. If you assign the value
4,294,967,295 to this integer, it also really contains the value -1. Subtracting the maximum
value the field will hold generally gives you the value that will be stored.
Question 4
What happens if I put a negative number into an unsigned variable?
Answer
As the previous answer indicated, your compiler may not signal any errors if you do this. The
compiler does the same wrapping as if you assigned a number that was too big. For instance,
if you assign –1 to an int variable that is two bytes long, the compiler will put the highest
number possible in the variable (65535).
Question 5
What are the practical differences between symbolic constants created with the #define
directive and those created with the const keyword?
Answer
The differences have to do with pointers and variable scope. Pointers and variable scope are
two very important aspects of C programming and are covered on Days 9 and 12, "Pointers,"
and "Variable Scope," respectively. For now, know that by using #define to create constants,
you can make your programs much easier to read.
Exercise 1
In what variable type would you best store the following values?
a. A person's weight in pounds.
b. Your annual salary.
c. The temperature.
d. A person's net worth.
Answer
a. unsigned int
b. If your expectations on yearly salary are not very high, a simple unsigned int variable
would work. If you feel you have potential to go above $65,535, you probably should use a
long. (Have faith in yourself; use a long.)
c. float (If you are only going to use whole numbers, use either int or long.)
d. Definitely a signed field. Either int, long, or float. See answer for 1b.
Exercise 2
Determine appropriate variable names for the values in exercise one.
Answer
(Answers for 2 and 3 are combined)
Remember, a variable name should be representative of the value it holds. A variable
declaration is the statement that initially creates the variable. The declaration may or may not
initialize the variable to a value. You can use any name for a variable, except the C keywords.
a. unsigned int age;
b. unsigned int weight;
c. float radius = 3;
d. long annual_salary;
e. float cost = 29.95;
f. const int max_grade = 100;
or
#define MAX_GRADE 100
g. float temperature;
h. long net_worth = -30000;
i. double star_distance;
Exercise 3
Write declarations for the variables in exercise two.
Answer
2.6: Summary
Numeric Variables
This unit has explored numeric variables, which are used by a C program to store data during
program execution. You've seen that there are two broad classes of numeric variables, integer
and floating point. Within each class are specific variable types. Which variable type— int,
long, float, or double—you use for a specific application depends on the nature of the data
to be stored in the variable. You've also seen that in a C program, you must declare a variable
before it can be used. A variable declaration informs the compiler of the name and type of a
variable.
Constants
This unit has also covered C's two constant types, literal and symbolic. Unlike variables, the
value of a constant cannot change during program execution. You type literal constants into
your source code whenever the value is needed. Symbolic constants are assigned a name that
is used wherever the constant value is needed. Symbolic constants can be created with the
#define directive or with the const keyword.