04
Variables
Give a value a name with ကိန်းရှင် ... ဖြစ်ပါစေ။
A variable is a named box that holds a value. Create it once, then use its name wherever the value is needed. Creating a variable is called declaring it.
Expected output
၁၈
၂.၅
၃၆
A declaration reads like a Burmese sentence:
| Zaka | Reads as | Part |
|---|---|---|
ကိန်းရှင် | "variable" | announces a new variable |
အသက် | "age" | the chosen name |
သည် | (subject) | |
ကိန်းပြည့် | "integer" | the kind of value it holds |
ဖြစ်၍ | "is, and" | joins the kind and the value |
တန်ဖိုးသည် | "its value" | |
၁၈ | 18 | the initial value (optional) |
ဖြစ်ပါစေ | "let it be" | the verb that declares |
။ | full stop |
Each variable has a kind, and it keeps that kind for its whole life. A ကိန်းပြည့်
variable holds an integer, and nothing else.
Starting values
Leave out ဖြစ်၍ တန်ဖိုးသည် and the initial value, and the variable starts at its
kind's default:
| Kind | Default |
|---|---|
| integers and decimal numbers | ၀ (zero) |
မှန်မှားတန်ဖိုး | မမှန် (false) |
စာလုံး | the null character '\0' |
Expected output
၀
မမှန်
၀.၀
The short form
The value can also come straight after the kind, without ဖြစ်၍ တန်ဖိုးသည်. These two
lines declare the same kind of variable with the same value:
Expected output
၁၈
၁၈
The short form is quicker to write. The long form keeps the kind and the value apart, which reads better when the value is long or starts with a kind word of its own. These pages use the long form.
The value must fit the kind
The initial value must suit the variable's kind. A decimal number cannot go into an integer variable:
Expected error
error[ZK0401]: expected isize, found f64
isize is the compiler's short name for plain ကိန်းပြည့်, and f64 for ဒဿမကိန်း.
The Error messages page lists all these short names.
Using a name before declaring it
A variable exists from its declaration onward, and not before. Using a name that was never declared is an error:
Expected error
error[ZK0301]: "အသက်" is not declared
Hands on
- Declare a variable for a height in centimetres and print it.
- Declare a
မှန်မှားတန်ဖိုးvariable with the value၅ သည် ၃ ထက် ကြီးသည်and print it.
Next: Constants.