Skip to main content
Logo image

Section 4.3 Introduction to Variables

We’ll now introduce the concept of a variable. As mentioned earlier, you can think of a variable as a storage location with a name associated to it by which you can refer to the contents of the storage location. A fundamental aspect of working with variables in C is that you need to decide and tell the computer up front what type of data (integer, character, etc) you wish to store in it. We call this process declaring the variable. Furthermore, it is good practice to assign a value to a variable right at the outset (we call this initializing) so that your variable holds a value that you control. If you try to use a variable that has not been declared, you will receive an error message from the compiler. Using a variable that has been declared but not initialized (not assigned a value) will lead to unpredictable results.

Investigate 4.1.

Can you deduce why uninitialized variables may give unpredictable results? What, if anything, do you think a variable that you have declared but not initialized contains?
How can we store numbers and recall them at different places in a program?

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

    What will be printed to the screen by the following program:
    #include <stdio.h>
    int main(void) {
        int money;
        money = 5;
        printf("I have %d dollars; that equals %d quarters.\n", money, 4*money);
        return 0;
    }
    
  • I have 5 dollars; that equals 20 quarters.
  • Great job!
  • I have %d dollars; that equals %d quarters.
  • Not quite - try again!
  • I have 5 dollars; that equals 4*5 quarters.
  • Not quite - try again!
  • I have 20 dollars; that equals 5 quarters.
  • Not quite - try again!
Hint.
There is a one-to-one match between format specifiers and parameters.