Reading — step 1 of 3
Conditional Execution
If/Else Statements
Conditional execution is what makes programs interesting. An if statement evaluates a condition and executes one of two branches based on the result.
Syntax
if (condition) thenBranch
if (condition) thenBranch else elseBranch
The condition is any expression. The branches are statements (often block statements):
if (temperature > 100) {
print "boiling";
} else {
print "not boiling";
}
Truthiness
The condition does not have to be a boolean. We define truthiness: false and nil are falsy, everything else is truthy. This matches Ruby and Lua. Python is more nuanced — 0, "", [], and None are all falsy.
if (0) → truthy (0 is not false or nil)
if (nil) → falsy
if ("") → truthy (empty string is not nil)
if (false)→ falsy
The Dangling Else Problem
Consider: if (a) if (b) print "yes"; else print "no";
Which if does the else belong to? This is the classic dangling else ambiguity. Our grammar resolves it by always binding else to the nearest if — the same convention used by C, Java, and most languages.
Parsing
ifStmt → "if" "(" expression ")" statement ( "else" statement )?
The else clause is optional. After parsing the then-branch, we check if the next token is else. If so, we parse the else-branch. Otherwise, we are done.
Execution
executeIf(stmt):
condition = evaluate(stmt.condition)
if isTruthy(condition):
execute(stmt.thenBranch)
else if stmt.elseBranch is not null:
execute(stmt.elseBranch)
Chained If/Else
There is no elif keyword in our language (unlike Python). Instead, we chain:
if (x < 0) {
print "negative";
} else if (x == 0) {
print "zero";
} else {
print "positive";
}
This works because the else branch is a statement, and an if is a statement. So else if is just else followed by another if statement — no special syntax needed.
Your Task
Implement if/else parsing and execution with correct truthiness rules and dangling else resolution.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…