A girl and a robot thinking together

Think together · Start with a story

A girl sees score = score + 2 and wonders: how can a number equal itself plus 2? Here, the equals sign is used differently from a math equation.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Look right firstOld score is 3
  2. Calculate3 plus 2 is 5
  3. Write on the leftUpdate score to 5

Assignment first evaluates the expression on the right, then writes the result to the variable on the left.

It describes an action, not a claim that “both sides are always equal.” So score can have a different value before and after the statement runs.

01What is assignment?

Look at this line of code:

score = 95;

It means: write the value produced by the expression on the right, 95, into the variable score on the left.

02Why is = not the same as mathematical equality?

In mathematics, x = x + 1 is not true.

But in a program:

x = x + 1;

It means read the old x, calculate x + 1, and then write the result back into x.

Read old value→Calculate x + 1→Write back to x

03Are initialization and assignment the same?

Not quite.

Initialization

int x = 10;

Give an object its initial value when creating it.

Assignment

x = 20;

Write a new value into an object that already exists.

04Can the right side be a calculation?

Of course. The right side is an expression, and it can be evaluated first:

int a = 3;
int b = 5;
int c;
c = a * 2 + b;

First calculate a * 2 + b, which gives 11, then assign it to c.

05Can you assign between different types?

Sometimes, but a type conversion may happen.

int x;
x = 3.9;

The floating-point number is converted to an integer here. Its fractional part is discarded, giving 3.

06Can anything be assigned to?

No. The left side must be a modifiable object.

10 = x;   // Error

The integer literal 10 is not a modifiable object, so it cannot go on the left side of an assignment.

What you have learned

  • Assignment writes the result of the right-side expression into the object on the left.
  • = is the assignment operator, not a mathematical equality symbol.
  • x = x + 1 means read the old value, calculate, and write the result back.
  • Initialization and assignment are not exactly the same concept.
  • Assigning between different types may cause a type conversion.

Next: + - * /: Let the Computer Do Math

Your turn to try

If score starts at 5, what is its value after running score = score + 2 twice?

Ready? Open to see the explanation

The first result is 7. The second statement reads the new 7, then adds 2 to get 9. Both statements do not use the original 5.