Why must variables be declared before use in EK9?
← Data Flow Safety · Ref: Q785
EK9 enforces strict top-to-bottom declaration order within a block. A variable must be declared before any line that references it. This prevents entire categories of bugs where variables are used with undefined or unexpected values.
WHY DECLARATION BEFORE USE
1. No undefined variable reads — every variable has a known value when first used
2. No hoisting surprises — unlike JavaScript, variables don't 'float' to the top
3. Clear data flow — reading top-to-bottom shows the complete picture
THIS EXAMPLE
The process() function declares greeting first, then uses it. The calculate() function declares both operands before using them in the result.
COMMON CAUSES
1. Rearranging code without moving declarations
2. Referencing a variable from a different scope
3. Typo creating a new name instead of using existing variable
See Q22 for variable declarations. See Q19 for assignment operators.
Example
defines module qa.dataflowsafety.usedbeforedefined defines program ShowGreeting() stdout <- Stdout() greeting <- "hello" stdout.println(greeting) first <- 10 second <- 20 result <- first + second stdout.println($result)
Common mistakes
E08010 — The variable 'greeting' is used on the println line before it is declared on the next line. Move the declaration before the first use. See ek9 -h E08010 for details.
Incorrect:
stdout.println(greeting)
greeting <- "hello"
Correct:
greeting <- "hello" stdout.println(greeting)
Other ways to ask this
- What triggers E08010 used before defined?
- Why does EK9 require declaration before use?
- How do I fix a variable used before it is declared?
Coming from another language?
Java: fields can be used before declaration in class scope, locals must be declared first. Python: no declaration needed, NameError at runtime if not assigned. Rust: must declare before use. Kotlin: must declare before use. Go: must declare before use. JavaScript: var is hoisted (surprising), let/const must be declared first. EK9: strict declaration-before-use in all scopes.
Keywords: E08010, hoisting, declare, variable, scope, use, defined, order, before