Variables

Review: Values, expression, and types

Values

Values are the things a computer can actually do things with.

They are represented by some actual bits in the computer’s memory.

We’ve learned about numbers and will soon learn about other kinds of values.

Some values have a literal form that we can write in our programs like 123 and 3.5.

Expressions

Expressions are the parts of a program that evaluate to a value.

The simplest expressions are single values, e.g. 10.

Compound expressions are made up of values and operators, e.g. 10 + 20.

Types

All expressions have a type which describes what kind of value it produces.

A literal value has a specific type: 10 is an int value; 1.5 is a double value.

The type of an expression is determined by the types of the values involved in the expression and the operators involved.

Why types?

If you’ve programmed in languages like Snap! or Javascript or Python, you might be wondering why we need types?

  • Efficiency

  • Detecting errors

Variables

Variables have two aspects.

In the text of a program, variables are names we can use to refer to values.

And when a program runs, a variable is essentially a place in the computer’s memory that holds a value.

Variables as expressions

In a program a variable can be used as an expression that evaluates to whatever its current value is.

As an expression, a variable can be used in a compound expression: a * 10 means multiply whatever value a currently holds by 10.

Variables in programs

Variables come into existance when they are declared.

When we declaring a variable we specify its name and its type:

int x;

This means that the name x (in the context where the declaration exists) is now a name that will always refer to some int value.

Variables are assigned values

This can happen when the variable is declared:

int x = 42;

Or it can happen later:

x = 84;

That’s only valid if x has been previously declared. (And was declared as a type that we can assign 84 to.)

We’re not in math class anymore

Variables can change

In math, = is an assertion that two things are the same x = y means that x and y must have the same value.

In programming, = means, take the value of the expression on the right side of the = and make that value the new value of the variable named on the left side.

(In math the closest thing to an assignment is something like “Let x be 10 …”.)

Variables are a form of abstraction

10 + 20 is a specific, concrete calculation that produces a single value.

a + b is an abstraction of the idea of adding two numbers together and can produce billions of different values.