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

(Romina) #1
myData pay94 age_limit amount QtlyIncome

Tip

C lets you begin a variable name with an underscore, but you shouldn’t do so. Some of
C’s built-in variables begin with an underscore, so there’s a chance you’ll overlap one
of those if you name your variables starting with underscores. Take the safe route and
always start your variable names with letters—I cannot underscore this point enough!
(See what I did there?)

The following examples of variable names are not valid:


Click here to view code image


94Pay my Age lastname,firstname

You ought to be able to figure out why these variable names are not valid: The first one, 94Pay,
begins with a number; the second variable name, my Age, contains a space; and the third variable
name, lastname, firstname, contains a special character (,).


Warning

Don’t name a variable with the same name as a function or a command. If you give a
variable the same name as a command, your program won’t run; if you give a variable
the same name as a function, you can’t use that same function name later in your
program without causing an error.

Defining Variables


Before you use a variable, you have to define it. Variable definition (sometimes called variable
declaration) is nothing more than letting C know you’ll need some variable space so it can reserve
some for you. To define a variable, you only need to state its type, followed by a variable name. Here
are the first few lines of a program that defines some variables:


Click here to view code image


main()
{
// My variables for the program
char answer;
int quantity;
float price;
/* Rest of program would follow */

The sample code just presented has three variables: answer, quantity, and price. They can
hold three different types of data: character data, integer data, and floating-point data. If the program
didn’t define these variables, it wouldn’t be able to store data in the variables.

Free download pdf