Data Types: Sized integers
● Beginner3 min
Int8 to Int32 and UInt8 to UInt64 hold whole numbers in less space, or only positive ones.
fn main() {
const small: UInt8 = 200
const low: Int8 = -128
print(small)
print(low)
}The program ran and printed:
kavach run sized.kav
200-128
A UInt8 holds 0 to 255, an Int8 -128 to 127. A number that can't fit is refused before the program runs, with the type to use instead:
fn main() {
const small: UInt8 = 300
print(small)
}The compiler refused the program:
kavach run sized-too-big.kav
error: `300` doesn't fit in `UInt8`, which holds 0 to 255: use `UInt16`Going past the limit while the program runs stops it, at the exact step. C and Go would wrap 255 + 1 round to 0 and carry on with a wrong number; Kavach never does:
fn fill(start: UInt8) {
let level = start
for _ in 0..10 {
level += 1
print(level)
}
}
fn main() {
fill(250)
}The program ran, then stopped with a panic:
kavach run overflow.kav
251252253254255panic: integer overflow: 255 + 1 doesn't fit in UInt8
When the compiler knows where the count starts and how often the loop runs, it doesn't wait for the run:
fn main() {
let level: UInt8 = 250
for _ in 0..10 {
level += 1
print(level)
}
}The compiler refused the program:
kavach run overflow-known.kav
error: this always panics: integer overflow: 255 + 1 doesn't fit in UInt8 (spec 1.8)The smallest value has no positive twin, so even dividing it by -1 doesn't fit, and is caught the same way:
fn main() {
const smallest: Int8 = -128
print(smallest / -1)
}The program ran, then stopped with a panic:
kavach run narrow-div.kav
panic: integer overflow: -128 / -1 doesn't fit in Int8What Kavach does for you
A number that can't fit is caught while compiling
const small: UInt8 = 300is refused before the program runs, and the message names the type that fits:UInt16.