04Variables
Blocks and scope
Group statements into a block; names declared inside remain inside.
A block groups several statements together. It opens with "do the following" and closes with "the tasks are done":
Expected output
အစ
၃
အဆုံး
| Zaka | Reads as | Job |
|---|---|---|
အောက်ပါတို့ကို လုပ်ဆောင်ပါ။ | "please do the following" | opens a block |
လုပ်ဆောင်စရာများ ပြီးပါပြီး။ | "the tasks are done" | closes the block |
On its own, a block does little. Its real job is to hold the statements of an if, a loop or a function. But it has one effect worth learning first: scope.
Scope
The scope of a name is the part of the program where the name can be used. A name declared inside a block can be used inside that block and nowhere else. After the closer, it is gone:
Expected error
error[ZK0301]: "ယာယီ" is not declared
Names from outside are visible inside, and blocks can sit inside other blocks:
Expected output
၁၁
Shadowing
An inner block can declare a name that exists outside as well. The inner one shadows the outer one: inside the block, the name means the new variable. When the block ends, the outer variable is back, unchanged.
Expected output
၁၀၀
၁
Four closing forms
The closer has four spellings that mean the same thing. Pick whichever reads best:
လုပ်ဆောင်စရာများ ပြီးပါပြီ။လုပ်ဆောင်စရာများ ပြီးပါပြီး။လုပ်ဆောင်စရာများ ပြီးဆုံးပါပြီ။လုပ်ဆောင်စရာများ ပြီးဆုံးပါပြီး။
These pages use ပြီးပါပြီး.
Hands on
- Declare a variable inside a block and attempt to print it after the block. Read the error.
- Nest three blocks, each shadowing the same name with a different value, and print it in each.
Next: Operators.