စံကား

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:

ZakaReads asPart
ကိန်းရှင်"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"
၁၈18the 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:

KindDefault
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:

စံကားZK0401

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:

စံကားZK0301

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.