First Steps in (C) Programming, introduction - What Is a Variable?
(Page 2 of 8 )
A variable is a specific piece of memory in your computer that consists of one or more contiguous bytes. Every variable has a name, and you can use that name to refer to that place in memory to retrieve what it contains or store a new data value there.
Let’s start with a program that displays your salary using the printf() function that you saw in Chapter 1. Assuming your salary is $10,000, you can already write that program very easily:
/* Program 2.1 What is a Variable? */ #include <stdio.h>
void main()
{
printf("My salary is $10000");
}
I’m sure you don’t need any more explanation about how this works; it’s almost identical to the programs you developed in Chapter 1. So how can you modify this program to allow you to customize the message depending on a value stored in memory? There are, as ever, several ways of doing this. What they all have in common, though, is that they use a variable.
In this case, you could allocate a piece of memory that you could call, say, salary, and store the value10000 in it. When you want to display your salary, you could use the name you’ve given to the variable, which issalary, and the value that’s stored in it (10000) would be displayed. Wherever you use a variable name in a program, the computer accesses the value that’s stored there. You can access a variable however many times you need to in your program. And when your salary changes, you can simply change the value stored in the variablesalaryand the whole program will carry on working with the new value. Of course, all these values will be stored as binary numbers inside the computer.
You can have as many variables as you like in a program. The value that each variable contains, at any point during the execution of that program, is determined by the instructions contained in your program. The value of a variable isn’t fixed, and it can change as many times as you need it to throughout a program.
Next: Variables That Store Numbers >>
More C++ Articles
More By Apress Publishing
|
This article is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530). Check it out today at your favorite bookstore. Buy this book now.
|
|