3.3. Another Example of Assignment
Time for another example. This bit of code demonstrates a
few more new things which we'll explain in a minute.
Example 3-3. displaying_variables.c
#include <stdio.h>
int
main()
{
short first_number = -5;
long second_number, third_number;
second_number = 20000 + 10000;
printf("the value of first_number is %hd\n", first_number);
printf("the value of second_number is %ld\n", second_number);
printf("the value of third_number is %ld\n", third_number);
return 0;
}
We've used a short and two
long variables. We could have used
int variables but chose to use other types to show
how similar they are. In the first line of main()
we declare a variable and give it a value all in one line. This is
pretty normal. The second line declares two variables at once by
separating them with a comma. This can be handily but code is often
more readable when variable declarations get a line to
themselves.
The third line is very like some code from the first example,
the addition operator produces the value 30000
which gets stored in second_number. The last thing
to point out is that instead of %d, the format
string of printf() contains %hd
for the short variable and %ld
for the long variables. These little groupings of characters are
called conversion specifiers. Each type of
variable has it's own conversion specifier. If you want to print a
single percent sign ("%") you must write
%%.
When you compile and run this you will see the value of your
variables. The value of third_number will be
strange. This is because it was never assigned a value. When you
declare a variable, the operating system allocates some memory for it.
You have no way of know what this memory was used for previously.
Until you give your variable a value, the data stored in it is
essentially random. Forgetting to assign a value to a variable is a
common mistake among beginning programmers.