Chapter 6
A Place to Put Stuff
In This Chapter
Understanding variables
Creating a specific variable type
Declaring variables in your code
Using signed or unsigned integers
Whipping up multiple variables at a time
Declaring and assigning at the same time
Putting variables to work
Human beings have obsessed over storing stuff ever since the Garden of Eden, when Adam stashed a grape in his belly button. That begs the question of why Adam would have a belly button, but that’s not my point. My point is that people enjoy storing things and creating places — boxes, closets, garages, and underground bunkers — in which to store that stuff.
Your C programs can also store things — specifically, various types of information. Computer storage is used to keep those items, but the containers themselves are called variables. They’re basic components of all computer programming.
Values That Vary
Your C programs can use two types of values: immediate and variable. An immediate value is one that you specify in the source code — a value you type or a defined constant. Variables are also values, but their contents can change. That’s why they’re called variables and not all-the-time-ables.
Setting up a quick example
Who likes to read a lot about something before they try it? Not me!
Exercise 6-1: Start a new project in Code::Blocks, name it ex0601, and type the source code, as shown in Listing 6-1. This project uses a single variable, x
, which is one of the first computer variable names mentioned in the Bible.
Listing 6-1: Your First Variable
#include <stdio.h>
int main()
{
int x;
x = 5;
printf("The value of variable x is %d.\n",x);
return(0);
}
Here’s a brief description using the line numbers assigned in the Code::Blocks editor on the computer screen:
Line 5 contains the variable's declaration. Every variable used in C must be declared as a specific variable type and assigned a name. The variable in Listing 6-1 is declared as an integer (int
) and given the name x
.
Line 7 assigns the value 5
to variable x
. The value goes on the right side of the equal sign. The variable goes on the left.
Line 8 uses the variable's value in the printf()
statement. The %d
conversion character is used because the variable contains an integer value. The conversion character must match the variable; in Line 8, you see one of each.
Build and run the code. The output looks like this:
The value of variable x is 5.
The following sections describe in further detail the mechanics of creating and using variables.
Introducing the variable types
C language variables are designed to hold specific types of values. If C were a genetic programming language, cats and dogs would go into the animal
variable type, and trees and ferns would go into the plant
variable type. C language variables work along these lines, with specific values assigned to matching types of variables.
The four basic variable types used in C are shown in Table 6-1.
Table 6-1 Basic C Language Variable Types
Type |
Description |
char |
Single-character variable; stores one character of information |
int |
Integer variable; stores integer (whole number) values |
float |
Floating-point variable; stores real numbers |
double |
Floating-point variable; stores very large or very small real numbers |
When you need to store an integer value, you use an int
variable. Likewise, if you're storing a letter of the alphabet, you use a char
variable. The information that the program requires dictates which variable type to declare.
The
char
and int
variable types are integer values. char
has a shorter range. It's used primarily to store characters — letters of the alphabet, numbers, and symbols — but it can also be used to store tiny integer values.
The
float
and double
types are both floating-point variables that can store very small or very large values.
A fifth type,
_Bool
, is used to store binary values, 1 or 0, often referred to as TRUE and FALSE, respectively. _Bool
, a loaner word from C++, must be written with the initial underscore character and a capital B. You may not find _Bool
used in many C program source code listings — most likely, to keep the code compatible with older compilers.
Using variables
Most, if not all, of your future C language programs will employ variables. Earlier in this chapter, Exercise 6-1 illustrates the basic three steps for using variables in the C language:
1. Declare the variable, giving it a variable type and a name.
2. Assign a value to the variable.
3. Use the variable.
All three steps are required for working with variables in your code, and these steps must be completed in that order.
To declare a variable, place a statement near the start of a function, such as the main()
function in every C program. Place the declaration after the initial curly bracket. (Refer to Listing 1-1.) The declaration is a statement on a line by itself, ending with a semicolon:
type name
;
type
is the variable type: char
, int
, float
, double
, and other specific types are introduced later in this chapter.
In the preceding example, name
is the variable's name. A variable's name must not be the name of a C language keyword or any other variable name that was previously declared. The name is case sensitive, although, traditionally, C language variable names are written in lowercase. If you want to be saucy, you can add numbers, dashes, or underscores to the variable name, but always start the name with a letter.
The equal sign is used to assign a value to a variable. The format is very specific:
variable
= value
;
Read this construct as, "The value of variable
equals value
."
Here, variable
is the variable's name. It must be declared earlier in the source code. value
is either an immediate value, a constant, an equation, another variable, or a value returned from a function. After the statement is executed, the variable
holds the value
that's specified.
Assigning a value to a variable satisfies the second step in using a variable, but you really need to do something with the variable to make it useful. Variables can be used anywhere in your source code that a value could otherwise be specified directly.
In Listing 6-2, four variable types are declared, assigned values, and used in printf()
statements.
Listing 6-2: Working with Variables
#include <stdio.h>
int main()
{
char c;
int i;
float f;
double d;
c = 'a';
i = 1;
f = 19.0;
d = 20000.009;
printf("%c\n",c);
printf("%d\n",i);
printf("%f\n",f);
printf("%f\n",d);
return(0);
}
Exercise 6-2: Type the source code for Listing 6-2 into the editor. Build and run.
The output looks something like this:
a
1
19.000000
20000.009000
In Line 10, the single character value a
is placed into char
variable a
. Single characters are expressed using single quotes in C.
In Line 15, you see the %c
placeholder used in the printf()
statement. That placeholder is designed for single characters.
Exercise 6-3: Replace Lines 15 through 18 with a single printf()
statement:
printf("%c\n%d\n%f\n%f\n",c,i,f,d);
Build and run the code.
The printf()
formatting string can contain as many conversion characters as needed, but only as long as you specify the proper quantity and type of variables for those placeholders, and in the proper order. The variables appear after the formatting string, each separated by a comma, as just shown.
Exercise 6-4: Edit Line 12 so that the value assigned to the f
variable is 19.8
and not 19.0
. Build and run the code.
Did you see the value 19.799999
displayed for variable f
? Would you say that the value is imprecise?
Exactly!
The float
variable type is single precision: The computer can accurately store only eight digits of the value. The internal representation of 19.8
is really the value 19.799999
because a single-precision (float
) value is accurate only to the eighth digit. For mathematical purposes, 19.799999
is effectively 19.8
; you can direct the code to display that value by using the %.1f
placeholder.
Exercise 6-5: Create a project named ex0605. In the source code, declare an integer variable blorf
and assign it the value 22
. Have a printf()
statement display the variable's value. Have a second printf()
statement display that value plus 16. Then have a third printf()
statement that displays the value of blorf
multiplied by itself.
Here’s the output from my sample program solution for Exercise 6-5:
The value of blorf is 22.
The value of blorf plus 16 is 38.
The value of blorf times itself is 484.
Exercise 6-6: Rewrite the source code for Exercise 6-5. Use the constant value GLORKUS
instead of the blorf
variable to represent the value 16
.
A variable name must always begin with a letter, but you can also start the name with an underscore, which the compiler believes to be a letter. Generally speaking, variable names that begin with underscores are used internally in the C language. I recommend avoiding that naming convention for now.
It isn’t a requirement that all variables be declared at the start of a function. Some programmers declare variables on the line before they’re first used. This strategy works, but it’s nonstandard. Most programmers expect to find all variable declarations at the start of the function.
Variable Madness!
I hope that you’re getting the hang of the variable thing. If not, please review the first part of this chapter. The variable is truly the heart of any programming language, by allowing you to code flexibility into your programs and have it do amazing things.
Using more-specific variable types
The C language’s variable types are more specific than what’s shown in Table 6-1. Depending on the information stored, you may want to use one of these more detailed variable declarations. Table 6-2 lists a buffet of C language variable types and also the range of values those types can store.
Table 6-2 More C Language Variable Types
Type |
Value Range |
printf() Conversion Character |
_Bool |
0 to 1 |
%d |
char |
–128 to 127 |
%c |
unsigned char |
0 to 255 |
%u |
short int |
–32,768 to 32,767 |
%d |
unsigned short int |
0 to 65,535 |
%u |
int |
–2,147,483,648 to 2,147,483,647 |
%d |
unsigned int |
0 to 4,294,967,295 |
%u |
long int |
–2,147,483,648 to 2,147,483,647 |
%ld |
unsigned long int |
0 to 4,294,967,295 |
%lu |
float |
1.17×10–38 to 3.40×1038 |
%f |
double |
2.22×10–308 to 1.79×10308 |
%f |
The value range specifies the size of the number you can store in a variable as well as whether negative numbers are allowed. The compiler may not always flag warnings that happen when you assign the wrong value to a variable type. So get it right when you declare the variable!
For example, if you need to store the value -10
, you use a short int
, int
, or long int
variable. You cannot use an unsigned int
, as the source code in Listing 6-3 demonstrates.
Listing 6-3: Oh, No — an Unsigned int!
#include <stdio.h>
int main()
{
unsigned int ono;
ono = -10;
printf("The value of ono is %u.\n",ono);
return(0);
}
Exercise 6-7: Create a project named ex0607, and type the source code shown in Listing 6-3. Note that the %u
conversion character is used for unsigned integer values. Build and run.
Here’s the output:
The value of ono is 4294967286.
The moral of the story: If your integer variable stores negative numbers, you can't use an unsigned
variable type.
The range of the
int
may be the same as the range of the short int
on some compilers. When in doubt, use a long int
.
You can specify
long
instead of long int
.
You can specify
short
instead of short int
.
The keyword
signed
can be used before any of the int
variable types, as in signed short int
for a short int
, although it's not necessary.
The
void
variable type also exists, although it's used to declare functions that return no values. Still, it's a valid variable type, though you'll probably never use it to declare a variable. See Chapter 10 for information on void
functions.
Creating multiple variables
I can find nothing in the rules to prevent starting a section with an exercise, so here you go:
Exercise 6-8: Create a program that uses the three integer variables shadrach
, meshach
, and abednego
. Assign integer values to each one, and display the result.
Here’s a copy of the output from the program generated by Exercise 6-8. It’s my version of the project:
Shadrach is 701
Meshach is 709
Abednego is 719
Your code can generate different text, but the underlying project should work. And give yourself a bonus if your answer matched my answer, which is given in Listing 6-4.
Listing 6-4: The Answer to Exercise 6-8
#include <stdio.h>
int main()
{
int shadrach, meshach, abednego;
shadrach = 701;
meshach = 709;
abednego = 719;
printf("Shadrach is %d\nMeshach is %d\nAbednego is %d\n",shadrach,meshach,abednego);
return(0);
}
When declaring multiple variables of the same type, you can specify all of them on the same line, as shown in Listing 6-4 (on Line 5). You don’t even have to put spaces after each name; the line could have easily been written
int shadrach,meshach,abednego;
I also stacked up the results in a single, long printf()
statement. The line wraps in Listing 6-4 because of this book's page width, and it may wrap on your computer screen as well. But if you type code that wraps, don't press the Enter key to start a new line.
printf("Shad is %d\nMesh is %d\nAbed is d\n",\
shadrach,meshach,abednego);
I shortened the names in this example so that the text fits on a line on this page. Between printf()
's formatting string and the variable list, right after the first comma, I typed a backslash and then pressed the Enter key. The effect is that the line is broken visually, but the compiler still sees it as a single statement. Visually, it looks better.
Assigning a value upon creation
C programmers love to load up code, often putting way too much stuff in a single statement. You can do that in C, but it often obfuscates the code, making it more difficult to read. Still, you can load up the code in ways that simply save time.
In Listing 6-5, the integer variable start
is created and assigned the value 0
upon creation. This combination saves typing another line of code that would assign 0
to the start
variable.
Listing 6-5: Declaring a Variable and Assigning a Value
#include <stdio.h>
int main()
{
int start = 0;
printf("The starting value is %d.\n",start);
return(0);
}
Exercise 6-9: Create a project named ex0609 using the source code shown in Listing 6-5.
Exercise 6-10: Modify the source code for Exercise 6-8 so that the three variables are created, and each is assigned values in three lines of code.
Reusing variables
Variables vary, so their contents can be changed at any time in the program. The examples shown elsewhere in this chapter use a variable only once and don’t alter its value. That’s pretty much the same as a constant, which makes them good examples for learning but poor examples for reality.
In your programming journey, variables are declared, and then their values may be, well, whatever. Not only that; it’s possible to reuse variables over and over — no harm done. That’s an easy example to show, as illustrated in Listing 6-6.
Listing 6-6: Variables Recycled
#include <stdio.h>
int main()
{
int prime;
prime = 701;
printf("Shadrach is %d\n",prime);
prime = 709;
printf("Meshach is %d\n",prime);
prime = 719;
printf("Abednego is %d\n",prime);
return(0);
}
Exercise 6-11: Create a new project, name it ex6011, and type the source code from Listing 6-6. As you can see, the variable prime
is used over and over, each time changing its value. The new value that's assigned replaces any existing value. Build and run the project.
The output from Exercise 6-11 is the same as from Exercise 6-10.
Listing 6-7 illustrates how variables can interact with each other.
Listing 6-7: Variables Mix It Up
#include <stdio.h>
int main()
{
int a,b,c;
a = 5;
b = 7;
c = a + b;
printf("Variable c=%d\n",c);
return(0);
}
Line 9 is the one to notice: The value of variable c
is assigned the sum of variables a
and b
. This calculation is made when the program runs, and then the result — whatever weirdo value that could be — is displayed.
Exercise 6-12: Create a project named ex0612 using the source code in Listing 6-7. Can you guess the output?
Exercise 6-13: Create a new project using the source code from Listing 6-7 as a starting point. Declare three float
variables, and assign values to two of them. Assign a value to the third variable by dividing the first variable by the second variable. Display the result.