70 lines
1.5 KiB
Plaintext
70 lines
1.5 KiB
Plaintext
# Milestone 5 foundation: booleans, comparisons, logical ops, if/else if/else.
|
|
|
|
printf c_func(format *c_char, ...) c_int
|
|
|
|
# Returns a distinct code per range using if / else if / else and comparisons.
|
|
classify func(n i32) i32 {
|
|
if n < 0 {
|
|
return 1
|
|
} else if n == 0 {
|
|
return 2
|
|
} else if n >= 100 {
|
|
return 3
|
|
} else {
|
|
return 4
|
|
}
|
|
}
|
|
|
|
# A bool-returning function with a visible side effect, used to prove
|
|
# short-circuit evaluation: it must only print when actually evaluated.
|
|
noisy func() bool {
|
|
_ = printf("rhs-evaluated\n")
|
|
return true
|
|
}
|
|
|
|
main func() i32 {
|
|
total i32 = 0
|
|
|
|
# comparisons drive if / else if / else
|
|
total = total + classify(-5) # 1
|
|
total = total + classify(0) # 2
|
|
total = total + classify(250) # 3
|
|
total = total + classify(42) # 4 -> 10
|
|
|
|
# bool variables and logical and / or / not
|
|
a :: true
|
|
b :: false
|
|
if a and !b {
|
|
total = total + 10 # 20
|
|
}
|
|
if b or a {
|
|
total = total + 10 # 30
|
|
}
|
|
if !(a and b) {
|
|
total = total + 5 # 35
|
|
}
|
|
|
|
# block scoping: inner bindings do not escape the block
|
|
x i32 = 1
|
|
if x == 1 {
|
|
inner_x i32 = 100
|
|
if inner_x == 100 {
|
|
total = total + 5 # 40
|
|
}
|
|
}
|
|
if x == 1 {
|
|
total = total + 2 # 42
|
|
}
|
|
|
|
# short-circuit: `false and noisy()` must NOT call noisy()
|
|
if false and noisy() {
|
|
_ = printf("unreachable-and\n")
|
|
}
|
|
# short-circuit: `true or noisy()` must NOT call noisy()
|
|
if true or noisy() {
|
|
_ = printf("or-taken\n")
|
|
}
|
|
|
|
return total # expect exit code 42
|
|
}
|