Show me ++ and -- being used in a real EK9 program.
← Operators and Expressions · Ref: Q996
The ++ and -- operators increment and decrement a variable by 1. They are standalone statements — write them on their own line.
INCREMENT:
counter++ adds 1 to counter
DECREMENT:
counter-- subtracts 1 from counter
OTHER MUTATION OPERATORS:
counter += 5 adds 5 to counter counter -= 3 subtracts 3 from counter
All mutation operators are standalone statements. They modify the variable directly and cannot be combined with other expressions on the same line.
Example
#!ek9 defines module qa.operators.incrementpractice defines program IncrementDemo() stdout <- Stdout() // ++ increments by 1 hitCount <- 0 hitCount++ hitCount++ hitCount++ stdout.println(`Hits: ${hitCount}`) // -- decrements by 1 livesRemaining <- 3 livesRemaining-- stdout.println(`Lives: ${livesRemaining}`) // += adds an amount totalScore <- 0 totalScore += 100 totalScore += 250 totalScore += 75 stdout.println(`Score: ${totalScore}`) // -= subtracts an amount totalScore -= 50 stdout.println(`After penalty: ${totalScore}`) // Counting in a loop evenCount <- 0 for number in 1 ... 10 if number mod 2 == 0 evenCount++ stdout.println(`Even numbers: ${evenCount}`)
Common mistakes
E07950 — ++ is a standalone statement in EK9 that does not return a value, so it cannot be used on the right of an assignment such as 'otherCount <- evenCount++'. Write 'evenCount++' on its own line. See ek9 -h E07950 for details.
Incorrect:
otherCount <- evenCount++
Correct:
evenCount++
Other ways to ask this
- How do I increment a counter in EK9?
- Give me a practical example of ++ in EK9
- How do I use ++ and += in EK9 code?
Coming from another language?
EK9 has ++ and -- as standalone statements. They modify the variable in place. Use += and -= for adding/subtracting other amounts.
Keywords: counter, decrement, increment, mutation, statement