You can use unary minus (-) in an OCL expression to negate one numeric value or numeric expression; it is for anyone writing calculations, derived attributes, or constraints.
Syntax
Unary minus is placed before the value or expression that you want to negate.
-value
-(expression)For example, the following expression evaluates to -5:
-(3 + 2)Unary minus and subtraction
The same - symbol has two uses. Unary minus acts on one operand and produces its negative value. Binary minus acts between two numeric operands and subtracts the right value from the left value.
| Expression | Meaning | Result |
|---|---|---|
-3
|
Unary minus applied to 3
|
-3
|
3 - 2
|
Binary minus: subtract 2 from 3
|
1
|
3 - -2
|
Subtract the negative value -2 from 3
|
5
|
For subtraction between two values, see minus.
Precedence
Unary minus has higher precedence than multiplication, division, addition, and binary subtraction. OCL therefore evaluates the unary minus first unless parentheses specify a different grouping.
| Expression | OCL evaluates it as | Result |
|---|---|---|
-3 + 2
|
(-3) + 2
|
-1
|
-(3 + 2)
|
Negate the result of 3 + 2
|
-5
|
-3 * 2
|
(-3) * 2
|
-6
|
Use parentheses when the intended grouping matters
Use parentheses to make it explicit whether you are negating one value or the result of a calculation.
-3 + 2 -- evaluates as (-3) + 2
-(3 + 2) -- negates the sumSee OCL precedence rules for the complete MDriven precedence order and the use of parentheses to change it.
Where to use it
Use unary minus wherever an OCL expression requires the negative of a numeric result. For example, you can negate a calculated value:
-(3 + 2)The expression first calculates 3 + 2, then returns the negative result, -5.
