Can I use ++ in an assignment like y <- x++ in EK9?
← Operators and Expressions · Ref: Q940
EK9 has ++ and -- but they are STATEMENT-ONLY. They modify the variable in place and produce no value. You cannot use them inside expressions.
STATEMENT-ONLY MEANS
counter++ CORRECT — standalone statement counter-- CORRECT — standalone statement y <- counter++ WRONG — ++ produces no value to assign if counter++ WRONG — ++ produces no Boolean
WHY THIS DESIGN
In C and Java, x++ returns the OLD value while ++x returns the NEW value. This causes subtle bugs:
// C or Java: which updates first? array[i++] = array[++j];
EK9 eliminates this entire bug category by making ++ and -- void operations.
IF YOU NEED THE OLD VALUE
saved <- Integer(counter) counter++ // saved has old value, counter has new value
Take a COPY with Integer(counter). A plain 'saved <- counter' names the SAME Integer object, and ++ changes that object in place, so both names would show the new value (see Q905).
This is the same design choice as Go, which also makes ++ and -- statements only.
See Q780 for detailed explanation. See Q238 for operator overview.
Example
defines module qa.operators.incrementstmt defines program IncrementDemo() stdout <- Stdout() counter <- 0 //Correct: ++ as standalone statement counter++ counter++ counter++ stdout.println(`After 3 increments: ${counter}`) //Correct: -- as standalone statement counter-- stdout.println(`After decrement: ${counter}`) //Copy before incrementing if you need the old value: //'previous <- counter' would share the object and ++ would change both previous <- Integer(counter) counter++ stdout.println(`Was ${previous}, now ${counter}`)
Common mistakes
E07950 — The ++ operator is statement-only in EK9 — it returns void and cannot be used in expressions. Take a copy with Integer(counter) on its own line, then increment on the next. See ek9 -h E07950 for details.
Incorrect:
previous <- counter++
Correct:
previous <- Integer(counter)
Other ways to ask this
- Are ++ and -- expressions or statements in EK9?
- Why can't I assign the result of ++ in EK9?
- How do increment and decrement work in EK9?
Coming from another language?
C/C++: pre/post increment as expressions, undefined behavior in complex expressions. Java: pre/post increment as expressions. Go: ++ and -- are statements only (same as EK9). Python: no ++ or -- at all. Rust: no ++ or -- at all. EK9: ++ and -- are statements only, like Go.
Keywords: statement, increment, assign, decrement, void, bug, expression, E07950