C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

5. Adding Variables to Your Programs


In This Chapter


  • Identifying kinds of variables

  • Naming variables

  • Defining variables

  • Storing data in variables


No doubt you’ve heard that computers process data. Somehow you’ve got to have a way to store that
data. In C, as in most programming languages, you store data in variables. A variable is nothing more
than a box in your computer’s memory that holds a number or a character. Chapter 2, “Writing Your
First C Program,” explained the different types of data: characters, strings, integers, and floating
points. This chapter explains how to store those types of data inside your programs.


Kinds of Variables


C has several different kinds of variables because there are several different kinds of data. Not just
any variable will hold just any piece of data. Only integer variables can hold integer data, only
floating-point variables can hold floating-point data, and so on.


Note

Throughout this chapter, think of variables inside your computer as acting like post
office boxes in a post office. Post office boxes vary in size and have unique numbers
that label each one. Your C program’s variables vary in size, depending on the kind of
data they hold, and each variable has a unique name that differentiates it from other
variables.

The data you learned about in Chapter 2 is called literal data (or sometimes constant data). Specific
numbers and letters don’t change. The number 2 and the character 'x' are always 2 and 'x'. A lot
of data you work with—such as age, salary, and weight—changes. If you were writing a payroll
program, you would need a way to store changing pieces of data. Variables come to the rescue.
Variables are little more than boxes in memory that hold values that can change over time.


Many types of variables exist. Table 5.1 lists some of the more common types. Notice that many of the
variables have data types (character, integer, and floating point) similar to that of literal data. After
all, you must have a place to store integers, and you do so in an integer variable.

Free download pdf