expressions.rst 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. Expressions
  2. ===========
  3. Solidity resembles the C family of languages. Expressions can use the following operators.
  4. Arithmetic operators
  5. ____________________
  6. The binary operators ``-``, ``+``, ``*``, ``/``, ``%``, and ``**`` are supported, and also
  7. in the assignment form ``-=``, ``+=``, ``*=``, ``/=``, and ``%=``. There is a
  8. unary operator ``-``.
  9. .. code-block:: solidity
  10. uint32 fahrenheit = celsius * 9 / 5 + 32;
  11. Parentheses can be used too, of course:
  12. .. code-block:: solidity
  13. uint32 celsius = (fahrenheit - 32) * 5 / 9;
  14. Operators can also come in the assignment form.
  15. .. code-block:: solidity
  16. balance += 10;
  17. The exponation (or power) can be used to multiply a number N times by itself, i.e.
  18. x :superscript:`y`. This can only be done for unsigned types.
  19. .. code-block:: solidity
  20. uint64 thousand = 1000;
  21. uint64 billion = thousand ** 3;
  22. Overflow checking is limited to types of 64 bits and smaller, if the `--math-overflow` command
  23. line argument is specified. No overflow checking is generated in `unchecked` blocks, like so:
  24. .. include:: ../examples/expression_unchecked.sol
  25. :code: solidity
  26. Bitwise operators
  27. _________________
  28. The ``|``, ``&``, ``^`` are supported, as are the shift operators ``<<``
  29. and ``>>``. These are also available in the assignment form ``|=``, ``&=``,
  30. ``^=``, ``<<=``, and ``>>=``. Lastly there is a unary operator ``~`` to
  31. invert all the bits in a value.
  32. Logical operators
  33. _________________
  34. The logical operators ``||``, ``&&``, and ``!`` are supported. The ``||`` and ``&&``
  35. short-circuit. For example:
  36. .. code-block:: javascript
  37. bool foo = x > 0 || bar();
  38. bar() will not be called if the left hand expression evaluates to true, i.e. x is greater
  39. than 0. If x is 0, then bar() will be called and the result of the ``||`` will be
  40. the return value of bar(). Similarly, the right hand expressions of ``&&`` will not be
  41. evaluated if the left hand expression evaluates to ``false``; in this case, whatever
  42. ever the outcome of the right hand expression, the ``&&`` will result in ``false``.
  43. .. code-block:: javascript
  44. bool foo = x > 0 && bar();
  45. Now ``bar()`` will only be called if x *is* greater than 0. If x is 0 then the ``&&``
  46. will result in false, irrespective of what bar() would return, so bar() is not
  47. called at all. The expression elides execution of the right hand side, which is also
  48. called *short-circuit*.
  49. Conditional operator
  50. ____________________
  51. The ternary conditional operator ``? :`` is supported:
  52. .. code-block:: javascript
  53. uint64 abs = foo > 0 ? foo : -foo;
  54. Comparison operators
  55. ____________________
  56. It is also possible to compare values. For, this the ``>=``, ``>``, ``==``, ``!=``, ``<``, and ``<=``
  57. is supported. This is useful for conditionals.
  58. The result of a comparison operator can be assigned to a bool. For example:
  59. .. code-block:: javascript
  60. bool even = (value % 2) == 0;
  61. It is not allowed to assign an integer to a bool; an explicit comparision is needed to turn it into
  62. a bool.
  63. Increment and Decrement operators
  64. _________________________________
  65. The post-increment and pre-increment operators are implemented by reading the variable's
  66. value before or after modifying it. ``i++``returns the value of ``i`` before incrementing,
  67. and ``++i`` returns the value of ``i`` after incrementing.
  68. this
  69. ____
  70. The keyword ``this`` evaluates to the current contract. The type of this is the type of the
  71. current contract. It can be cast to ``address`` or ``address payable`` using a cast.
  72. .. include:: ../examples/expression_this.sol
  73. :code: solidity
  74. Function calls made via this are function calls through the external call mechanism; i.e. they
  75. have to serialize and deserialise the arguments and have the external call overhead. In addition,
  76. this only works with public functions.
  77. .. include:: ../examples/expression_this_external_call.sol
  78. :code: solidity
  79. .. note::
  80. On Solana, this gives the account of contract data. If you want the account with the program code,
  81. use ``tx.program_id``.
  82. type(..) operators
  83. __________________
  84. For integer values, the minimum and maximum values the types can hold are available using the
  85. ``type(...).min`` and ``type(...).max`` operators. For unsigned integers, ``type(..).min``
  86. will always be 0.
  87. .. include:: ../examples/type_operator.sol
  88. :code: solidity
  89. The `EIP-165 <https://eips.ethereum.org/EIPS/eip-165>`_ interface value can be retrieved using the
  90. syntax ``type(...).interfaceId``. This is only permitted on interfaces. The interfaceId is simply
  91. an bitwise XOR of all function selectors in the interface. This makes it possible to uniquely identify
  92. an interface at runtime, which can be used to write a `supportsInterface()` function as described
  93. in the EIP.
  94. The contract code for a contract, i.e. the binary WebAssembly or BPF, can be retrieved using the
  95. ``type(c).creationCode`` and ``type(c).runtimeCode`` fields, as ``bytes``. On EVM,
  96. the constructor code is in the ``creationCode`` and all the functions are in
  97. the ``runtimeCode``. Parity Substrate and Solana use the same
  98. code for both, so those fields will evaluate to the same value.
  99. .. include:: ../examples/retrieve_contract_code.sol
  100. :code: solidity
  101. .. note::
  102. ``type().creationCode`` and ``type().runtimeCode`` are compile time constants.
  103. It is not possible to access the code for the current contract. If this were possible,
  104. then the contract code would need to contain itself as a constant array, which would
  105. result in an contract of infinite size.
  106. Ether and time units
  107. ____________________
  108. Any decimal numeric literal constant can have a unit denomination. For example
  109. ``10 minutes`` will evaluate to 600, i.e. the constant will be multiplied by the
  110. multiplier listed below. The following units are available:
  111. =========== =========================
  112. Unit Multiplier
  113. ``seconds`` 1
  114. ``minutes`` 60
  115. ``hours`` 3600
  116. ``days`` 86400
  117. ``weeks`` 604800
  118. ``wei`` 1
  119. ``ether`` 1_000_000_000_000_000_000
  120. =========== =========================
  121. Note that ``ether``, ``wei`` and the other Ethereum currency denominations are available when not
  122. compiling for Ethereum, but they will produce warnings.
  123. Casting
  124. _______
  125. Solidity is very strict about the sign of operations, and whether an assignment can truncate a
  126. value. You can force the compiler to accept truncations or sign changes by adding an
  127. explicit cast.
  128. Some examples:
  129. .. code-block:: solidity
  130. function abs(int bar) public returns (int64) {
  131. if (bar > 0) {
  132. return bar;
  133. } else {
  134. return -bar;
  135. }
  136. }
  137. The compiler will say:
  138. .. code-block:: none
  139. implicit conversion would truncate from int256 to int64
  140. Now you can work around this by adding a cast to the argument to return ``return int64(bar);``,
  141. however it is idiomatic to match the return value type with the argument type. Instead, implement
  142. multiple overloaded abs() functions, so that there is an ``abs()`` for each type.
  143. It is allowed to cast from a ``bytes`` type to ``int`` or ``uint`` (or vice versa), only if the length
  144. of the type is the same. This requires an explicit cast.
  145. .. code-block:: solidity
  146. bytes4 selector = "ABCD";
  147. uint32 selector_as_uint = uint32(selector);
  148. If the length also needs to change, then another cast is needed to adjust the length. Truncation and
  149. extension is different for integers and bytes types. Integers pad zeros on the left when extending,
  150. and truncate on the right. bytes pad on right when extending, and truncate on the left. For example:
  151. .. code-block:: solidity
  152. bytes4 start = "ABCD";
  153. uint64 start1 = uint64(uint4(start));
  154. // first cast to int, then extend as int: start1 = 0x41424344
  155. uint64 start2 = uint64(bytes8(start));
  156. // first extend as bytes, then cast to int: start2 = 0x4142434400000000
  157. A similar example for truncation:
  158. .. code-block:: javascript
  159. uint64 start = 0xdead_cafe;
  160. bytes4 start1 = bytes4(uint32(start));
  161. // first truncate as int, then cast: start1 = hex"cafe"
  162. bytes4 start2 = bytes4(bytes8(start));
  163. // first cast, then truncate as bytes: start2 = hex"dead"
  164. Since ``byte`` is an array of one byte, a conversion from ``byte`` to ``uint8`` requires a cast. This is
  165. because ``byte`` is an alias for ``bytes1``.