| 1 | (* ABS(x) is x without its sign, of x's type (report section 6.1): of |
| 2 | each signed type at its own width, where the smallest value gives |
| 3 | itself, as -x does; of each unsigned type, which is x itself; of an |
| 4 | operator's result, beside other values; and of constants, typed and |
| 5 | untyped, in a constant too. *) |
| 6 | module Abs; |
| 7 | import Out; |
| 8 | |
| 9 | const |
| 10 | Five = ABS(-5); (* untyped *) |
| 11 | Big = ABS(MIN(I64) + 1); (* untyped, the largest I64 *) |
| 12 | Byte = ABS(I8(-128)); (* typed, gives itself *) |
| 13 | Word = ABS(U16(65535)); |
| 14 | Sum = ABS(-2) + ABS(3) * 10; (* 32 *) |
| 15 | |
| 16 | proc show(n: I64); |
| 17 | begin |
| 18 | Out.int(n); Out.char(' '); |
| 19 | end; |
| 20 | |
| 21 | proc i8(x: I8); |
| 22 | begin |
| 23 | show(I64(ABS(x))); show(I64(-x)); |
| 24 | end; |
| 25 | |
| 26 | proc i16(x: I16); |
| 27 | begin |
| 28 | show(I64(ABS(x))); show(I64(-x)); |
| 29 | end; |
| 30 | |
| 31 | proc i32(x: I32); |
| 32 | begin |
| 33 | show(I64(ABS(x))); show(I64(-x)); |
| 34 | end; |
| 35 | |
| 36 | proc i64(x: I64); |
| 37 | begin |
| 38 | show(I64(ABS(x))); show(I64(-x)); |
| 39 | end; |
| 40 | |
| 41 | proc int(x: INT); |
| 42 | begin |
| 43 | show(I64(ABS(x))); show(I64(-x)); |
| 44 | end; |
| 45 | |
| 46 | proc main*; |
| 47 | var a, b: I8; u8: U8; u16: U16; u32: U32; u64: U64; n: INT; t: I8; |
| 48 | begin |
| 49 | i8(0); i8(7); i8(-7); i8(127); i8(-127); i8(-128); Out.ln; |
| 50 | i16(5); i16(-5); i16(32767); i16(-32768); Out.ln; |
| 51 | i32(9); i32(-9); i32(2147483647); i32(-2147483648); Out.ln; |
| 52 | i64(1); i64(-1); i64(MAX(I64)); i64(MIN(I64)); Out.ln; |
| 53 | int(-42); int(42); int(MIN(INT)); Out.ln; |
| 54 | |
| 55 | u8 := 200; u16 := 65535; u32 := 0FFFFFFFFH; u64 := 0FFFFFFFFFFFFFFFFH; |
| 56 | show(I64(ABS(u8))); show(I64(ABS(u16))); show(I64(ABS(u32))); Out.hex(ABS(u64), 16); Out.ln; |
| 57 | |
| 58 | (* the sum wraps to -128 in an I8, which ABS keeps *) |
| 59 | a := 100; b := 28; |
| 60 | t := a + b; |
| 61 | show(I64(t)); show(I64(ABS(I8(a + b)))); show(I64(ABS(a - b - 100))); Out.ln; |
| 62 | |
| 63 | (* beside other values on the stack *) |
| 64 | n := -3; |
| 65 | show(10 * ABS(n) + ABS(n - 4) * ABS(-n)); Out.ln; |
| 66 | |
| 67 | show(Five); show(Big); show(I64(Byte)); show(I64(Word)); show(Sum); Out.ln; |
| 68 | end; |
| 69 | |
| 70 | end Abs. |