Increment (++) and Decrement (--)

The increment ++ and decrement -- operators add or subtract 1 from a variable. They can be used in prefix form (before the variable) or postfix form (after the variable).

Syntax

++variable // Prefix increment variable++ // Postfix increment --variable // Prefix decrement variable-- // Postfix decrement

Prefix vs Postfix

The key difference is when the value is returned:

  • Prefix (++x): Increments first, then returns the new value
  • Postfix (x++): Returns the current value, then increments

Examples

Basic usage:

let x = 5;
x++;              // x is now 6
print(x);         // Output: 6

let y = 10;
y--;              // y is now 9
print(y);         // Output: 9

Prefix vs Postfix difference:

let a = 5;
let b = ++a;      // a becomes 6, then b = 6
print(a, b);      // Output: 6 6

let c = 5;
let d = c++;      // d = 5, then c becomes 6
print(c, d);      // Output: 6 5

In Loops

Commonly used in for loops:

// Traditional C-style for loop with increment
for (let i = 0; i < 5; i++) {
    print(i);     // Output: 0, 1, 2, 3, 4
}

// Counting down
for (let i = 5; i > 0; i--) {
    print(i);     // Output: 5, 4, 3, 2, 1
}

Game Use Cases

Counting lives:

let lives = 3;

fn takeDamage() {
    lives--;
    if (lives <= 0) {
        print("Game Over!");
    } else {
        print("Lives remaining:", lives);
    }
}

takeDamage();     // Lives remaining: 2
takeDamage();     // Lives remaining: 1
takeDamage();     // Game Over!

Collecting points:

let score = 0;

fn collectCoin() {
    score++;
    print("Score:", score);
}

fn collectBonus() {
    // Bonus gives 10 points
    for (let i = 0; i < 10; i++) {
        score++;
    }
    print("Bonus collected! Score:", score);
}

Requirements

  • The operand must be a variable (not a literal or expression)
  • The variable must be numeric (int or float)
  • Float variables are incremented by 1.0
  • Cannot be used on const variables

Restrictions

// These will cause errors:
let x = 5++;
        // ^^ Error: expected semicolon

let y = (2 + 3)++;
        // ^^ Error: expected variable name

const z = 10;
z++;    // Error: cannot modify const variable

See Also