How to Reuse Variables when Programming in C

By Dan Gookin

Variables vary, so their contents can be changed at any time in the program. In your C 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.

VARIABLES RECYCLED

#include <stdio.h>
int main()
{
  int prime;
  prime = 701;
  printf("Shadrach is %dn",prime);
  prime = 709;
  printf("Meshach is %dn",prime);
  prime = 719;
  printf("Abednego is %dn",prime);
  return(0);
}

Exercise 1: Create a new project, name it ex6011, and type the source code from Variables Recycled. 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.

This listing illustrates how variables can interact with each other:

VARIABLES MIX IT UP

#include <stdio.h>
int main()
{
  int a,b,c;
  a = 5;
  b = 7;
  c = a + b;
  printf("Variable c=%dn",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 2: Create a project named ex0612 using the source code in Variables Mix It Up. Can you guess the output?

Exercise 3: Create a new project using the source code from Variables Mix It Up 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.