Skip to content
Kavachकवच

Operators: Arithmetic

● Beginner3 min

+ - * / work as in school; % is the remainder and ** the power.

fn main() {
    print(7 + 2)
    print(7 - 2)
    print(7 * 2)
    print(7 / 2)
    print(7 % 2)
    print(2 ** 10)
    print(7.0 / 2.0)
}

The compiler warned, then the program ran:

kavach run arithmetic.kav

warning: `7 / 2` is `3`: whole numbers divide to a whole number. Write `7.0 / 2.0` for a fraction, or `7.div_floor(2)` when the whole part is meant (spec 1.8)95143110243.5
arithmetic.kav: Kavach code, then what running it prints
  • Two Ints divide to an Int: 7 / 2 is 3. Use floats, 7.0 / 2.0, for 3.5.
  • Written with two numbers that don't divide evenly, as 7 / 2 is here, it also gets a warning: it rarely means what it says. Write 7.div_floor(2) when the whole part is what you want.
  • 2 ** 10 is 2 to the power 10.
  • A whole-number result too big for its type stops the program; it never wraps to a wrong number.

Negative numbers: two ways to divide

fn main() {
    print(-7 / 2)
    print((-7).div_floor(2))
    print(-7 % 3)
    print((-7).mod(3))
    const today = 1
    print((today - 3).mod(7))
}

The compiler warned, then the program ran:

kavach run floor.kav

warning: `-7 / 2` is `-3`: whole numbers divide to a whole number. Write `-7.0 / 2.0` for a fraction, or `(-7).div_floor(2)` when the whole part is meant (spec 1.8)-3-4-125
floor.kav: Kavach code, then what running it prints
  • / and % round toward zero, as C and Java do: -7 / 2 is -3, and -7 % 3 is -1.
  • div_floor rounds down, and mod gives a remainder with the sign of the number you divide by, as Python's // and % do: -4 and 2.
  • Use mod for anything that wraps around, such as days of the week: 3 days before day 1 is day 5, never -2.

What Kavach does for you

  • Overflow is caught, never wrapped

    An integer that goes past its type's limit stops the program with a clear message, instead of quietly turning into a wrong number. When the compiler knows the values, even through a loop over known numbers, it is a compile error.

    spec 1.8