CodeBlanks Logo Icon CodeBlanks

Assignment operators

Learn shortcut assignments with =, +=, -= and ++/--.

Assignment operators

The basic assignment operator is =: x = 5;. Besides it, compound assignment operators provide shortcuts.

x += 5 actually means x = x + 5. Similarly there are -=, *=, /=, %=. They make code shorter and clearer.

++ and -- increase or decrease by one: x++ is the same as x = x + 1. They are common in loops.

Practice Compound assignment

Start with var x = 10;. Do x += 5; and print print(x). Then do x++; and print print(x) again.

Starter code

main.dart
// Use compound assignment

Sample solution

main.dart
void main() {
  var x = 10;
  x += 5;
  print(x);
  x++;
  print(x);
}

Expected output

15
16

Increment and decrement

++ increases a variable by 1; -- decreases it by 1. x++ is the same as x = x + 1; x-- is the same as x = x - 1.

There are prefix and postfix forms: ++x (prefix) increments then returns; x++ (postfix) returns then increments. Used alone they are the same.

In loops i++ is common: for (var i = 0; i < 5; i++). This advances the counter by one each time.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does x += 5 do?

  • Multiplies x by 5
  • Sets x to 5
  • Throws an error
  • Adds 5 to x (x = x + 5) Correct answer

Explanation: += is a shortcut for x = x + 5.

2 Compound assignment sign

Question
x ____= 3; // x = x + 3
Answer
x += 3; // x = x + 3

Explanation: It is part of the += sign.

3 Assignment operators

Term Meaning
= Assignment
+= Add and assign
++ Increment
-- Decrement

All lessons in Beginner