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

(Romina) #1

You can define more than one variable of the same data type on the same line. For example, if you
wanted to define two character variables instead of just one, you could do so like this:


Click here to view code image


main()
{
// My variables for the program
char first_initial;
char middle_initial;
/* Rest of program would follow. */

or like this:


Click here to view code image


main()
{
// My variables for the program
char first_initial, middle_initial;
/* Rest of program would follow. */

Tip

Most C variables are defined after an opening brace, such as the opening brace that
follows a function name. These variables are called local variables. C also lets you
create global variables by defining the variables before a function name, such as
before main(). Local variables are almost always preferable to global variables.
Chapter 30, “Organizing Your Programs with Functions,” addresses the differences
between local and global variables, but for now, all programs stick with local
variables.

Storing Data in Variables


The assignment operator puts values in variables. It’s a lot easier to use than it sounds. The
assignment operator is simply the equals sign (=). The format of putting data in variables looks like
this:


variable = data;

The variable is the name of the variable where you want to store data. You must have defined the
variable previously, as the preceding section explained. The data can be a number, character, or
mathematical expression that results in a number. Here are examples of three assignment statements
that assign values to the variables defined in the preceding section:


answer = 'B';
quantity = 14;
price = 7.95;

You also can store answers to expressions in variables:

Free download pdf