Instant properties: abs

The instant property abs represents the absolute value of the given int8, int16, int32, int64, float, point or rect operand.

Declaration

Form 1:

int8 int8. abs

int16 int16.abs

int32 int32.abs

int64 int64.abs

float float.abs

Form 2:

point point.abs

rect rect. abs

Discussion

The instant property abs returns the absolute value of the operand in context of which it has been evaluated. The resulting data type corresponds to the type of the original operand. For example, if used in context of an int8 operand, the result of the operation is int8 too. In its first form the instant property simply removes the sign from the given operand and returns its positive version. For example:

var int8 n1 = -65; var int8 n2 = 65; var int8 result1 = n1.abs; // result1 = 65 var int8 result2 = n2.abs; // result2 = 65

The second form is intended for usage in context of more complex data types containing multiple components each. For example, an operand of type point contains the int32 components x and y. In this case the instant property abs is applied to each component individually resulting in an absolute point value. For example:

var point p1 = <-20,35>; var point p2 = <20,-35>; var point p3 = <-20,-35>; var point result1 = p1.abs; // result1 = <20,35> var point result2 = p2.abs; // result2 = <20,35> var point result3 = p3.abs; // result3 = <20,35>

Since the instant property abs returns a value of data type corresponding to the of the original operand, the property is ideal to calculate with an absolute value of the operand without needing to type cast the result back to e.g. int8. This, however, may lead to a problem: if the integer operand has its maximum negative value (e.g. -128 in case of int8), there is no corresponding positive value in the same data type (e.g. in int8 the maximum positive value is 127). The abs instant property returns in such case the original and unchanged -128 value. For such operations a second set of uabs instant properties is available. These return the unsigned version of the original data type, e.g. uint8 in case of int8 operand. For example:

var int8 n1 = -127; var int8 n2 = -128; var int8 result1 = n1.abs; // result1 = 127 var int8 result2 = n2.abs; // result2 = -128 OVERFLOW ERROR var uint8 result3 = n2.uabs; // result3 = 128

Please note, the instant property abs is read-only. The write access to this property is not allowed.