Does EK9 have ++ and -- operators? What are the rules?

← Operators and Expressions · Ref: Q967

YES, EK9 has ++ and -- operators. But they are STATEMENT-ONLY — they cannot be used in expressions.

VALID (statement-only):

  count++         increments count by 1
  count--         decrements count by 1
  temperature++   increments temperature

INVALID (not an expression):

  y <- x++        COMPILE ERROR — ++ cannot be used in an expression
  total <- count++ + 5    COMPILE ERROR
  if x++ > 10     COMPILE ERROR

WHY STATEMENT-ONLY?

Mutating operators (++, --, +=, -=) return 'this' — the SAME object, not a copy. This means y <- x++ would make y and x point to the SAME object (aliasing). This is EK9's most dangerous gotcha and is prevented by the compiler.

Bridge: Like C++/Java's ++ but restricted to statements. Similar to how Python chose not to have ++ at all — EK9 allows it but prevents the aliasing danger.

OTHER MUTATING OPERATORS:

  x += 5    statement-only, adds 5 to x
  x -= 3    statement-only, subtracts 3 from x
  x *= 2    statement-only, multiplies x by 2

All mutating operators follow the same rule: statement-only, no expression use.

See Q905 for mutating operator aliasing details. See Q241 for the full mutation operator list.

Example

defines module qa.operators.incrementrules

  defines program

    IncrementDemo()
      stdout <- Stdout()

      // ++ as statement — VALID
      counter <- 0
      counter++
      stdout.println(`After ++: ${counter}`)

      counter++
      counter++
      stdout.println(`After two more ++: ${counter}`)

      // -- as statement — VALID
      counter--
      stdout.println(`After --: ${counter}`)

      // += as statement — VALID
      counter += 10
      stdout.println(`After += 10: ${counter}`)

      // -= as statement — VALID
      counter -= 3
      stdout.println(`After -= 3: ${counter}`)

      // The correct pattern when you need the value:
      // Increment first, then use the variable
      score <- 100
      score++
      displayScore <- score
      stdout.println(`Score after increment: ${displayScore}`)

      // NOT: displayScore <- score++  (COMPILE ERROR)

Common mistakes

E07950 — The '++' operator is statement-only in EK9 — it cannot be used inside an expression like 'displayScore <- score++'; increment on its own line first, then use the variable. See ek9 -h E07950 for details.

Incorrect:

      displayScore <- score++

Correct:

      displayScore <- score
Other ways to ask this
  • Can I use ++ in EK9?
  • How does increment work in EK9?
  • Are ++ and -- expressions or statements in EK9?
  • Why can't I write y <- x++ in EK9?

Coming from another language?

Java: i++ works in expressions (causes bugs). C: i++ is expression (undefined behaviour in some cases). Python: no ++ at all. EK9: ++ exists but is statement-only — the safest of all approaches.

Keywords: mutation, increment, decrement, aliasing, statement only