LEVIATHAN v962456e · 962456eee1

Expressions

Prefix operators

The operand types accepted by the unary operators !, - and ~, and the results they produce.

since 0.1.0-alpha.1linuxwindowswasm

Description

Each of the three prefix operators requires an operand of a matching type. The compiler checks this statically, and a mismatch on a primitive is a compile error of the form no operator 'X' on 'T'. There is no silent coercion: there is no truthiness (a number or a string never stands for a bool) and no implicit number-to-bool conversion.

operator operand result
! bool only bool
- any numeric type the operand's own type
~ any integer type the operand's own type, reduced to its width

The valid forms

bool flag = true;
console.writeln(!flag);
console.writeln(!(3 > 4));

console.writeln(-7);
console.writeln(-2.5);
int8 lowest = -128;
console.writeln(-lowest);
uint one = 1;
console.writeln(-one);

byte zero = 0;
console.writeln(~zero);
console.writeln(~5);

string name = "";
console.writeln(!name.isEmpty());
false
true
-7
-2.500000
-128
4294967295
255
-6
false

Rules

  • ! accepts only a bool and yields a bool. !"x", !0, !'c' and !1.5 are compile errors, including inside a comparison such as flag == !name. To negate a test, write an explicit predicate: !name.isEmpty() or n != 0.
  • - accepts the numeric types (int, byte, int8, int16, int32, uint, float, float8, float16, float32) and yields the operand's own type. An integer wraps at its width: -lowest for an int8 holding -128 is -128, and -one for a uint holding 1 is 4294967295. On a narrow float, - flips the sign bit and keeps the format.
  • ~ accepts the integer types only, yields the operand's own type and reduces the result to its width: the complement of a byte holding 0 is 255, not -1. There is no float form of ~ at any width.
  • A prefix operator on a class, a union or an unresolved generic value is not rejected by the compiler. Do not rely on it: such a value reaching a prefix operator at run time is a defect in the program.

Examples

console.writeln(!"x");
// error: no operator '!' on 'string'
console.writeln(!0);
// error: no operator '!' on 'int'
console.writeln(-"s");
// error: no operator '-' on 'string'
console.writeln(-true);
// error: no operator '-' on 'bool'
console.writeln(~1.5);
// error: no operator '~' on 'float'
console.writeln(~true);
// error: no operator '~' on 'bool'
not run — shows a compile error

Notes

  • Postfix forms bind tighter than prefix operators, and prefix operators bind tighter than every binary operator: -2.abs() is -(2.abs()). See lang.operator-precedence.

See also

  • bool — The boolean type: a value is either true or false.
  • int — The signed 64-bit integer type, the default type of whole numbers.