What is a variable?

In a course on mathematics we might define the word variable to mean “the unknown quantity.”
We have an equation x^2 - 9 = 0 and we want to know: for which values of x does the equation hold true?

In a course on physics, we might define the word variable to mean “the adjustable quantity.” We have an electrical circuit. We know the resistance in the circuit. We can control the voltage. We can measure the current. We want to see how changes in voltage affect current.

In a course on computer science, we define the word variable to mean “a named location in the computer’s memory.”

That’s it! If we know these six attributes, we know everything that there is to know about a variable.

A variable has six attributes:

  • A variable has a name.
  • A variable has a location in the computer’s memory. The location is an address. Maybe the computer’s memory has a capacity of 8 gigabytes. The address specifies which of the 8 billion bytes belongs to our variable.
  • A variable has a value. We will store some number in that location.
  • A variable has a type. That number is a code. It might represent a whole number, a fraction, a character (for example, letter, digit, punctuation mark), a true or false value, or something else.
  • A variable has a scope. The scope is the part of the text of the computer program in which we can refer to this variable.
  • A variable has a lifetime. A program might create a variable midway through its execution. A program might dispose of a variable before it finishes executing. This time between the variable’s birth and death is its lifetime.

But… you might have other questions:

Which of these attributes can a programmer control? How?

Which types does the programming language define for the programmer?

Does the programming language give the programmer a means to define new types?

How do programmers create variables on the fly?

How can programmers discard variables they no longer need?

There is much more to say. Next time!