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 abooland yields abool.!"x",!0,!'c'and!1.5are compile errors, including inside a comparison such asflag == !name. To negate a test, write an explicit predicate:!name.isEmpty()orn != 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:-lowestfor anint8holding-128is-128, and-onefor auintholding1is4294967295. 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 abyteholding0is255, 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()). Seelang.operator-precedence.