Unary Operators
Introduction
Unary operators are operators that operate on a single operand. In Solidity, there are several unary operators that you can use to modify the value of a variable or expression. In this blog post, we'll discuss each of these operators in detail, and provide examples to illustrate their usage.
- Logical Negation (!) The logical negation operator (!) returns the opposite boolean value of its operand. If the operand is true, the operator returns false. If the operand is false, the operator returns true. Here's an example:
bool a = true;
bool b = !a; // b = false
- Bitwise Negation - The bitwise negation operator aka ~~ inverts all the bits of its operand. This operator can only be used with integer types (int, uint). Here's an example:
uint8 a = 5; // 0000 0101
uint8 b = ~a; // 1111 1010`
- Unary Plus (+) The unary plus operator (+) is used to explicitly indicate that a value is positive. It is often used to convert a negative value to a positive value. This operator can be used with numeric types (int, uint, fixed, ufixed). Here's an example:
int8 a = -5;
int8 b = +a; // b = -5
- Unary Minus (-) The unary minus operator (-) is used to negate the value of its operand. This operator can be used with numeric types (int, uint). Here's an example:
int8 a = 5;
int8 b = -a; // b = -5
- Type Casting Type casting is the process of converting a value from one type to another. Solidity provides unary operators to cast values from one type to another. Here are some examples:
int16 a = 32767;
int8 b = int8(a); // b = -1 (overflow)
uint8 c = uint8(a); // c = 255 (overflow)
fixed d = fixed(a); // d = 32767.0
ufixed e = ufixed(a); // e = 32767.0
- Delete The delete operator is used to free storage or memory. When you delete a variable, its value is set to the default value of its type. For value types, the default value is 0, and for reference types, the default value is null. Here's an example:
uint[] storage a = [1, 2, 3];
delete a; // a = []
Conclusion
That's it! These are the unary operators available in Solidity. By understanding their usage and syntax, you can write more efficient and effective Solidity code.