From 215f41776c867187f460f52f20fd87bea83bb499 Mon Sep 17 00:00:00 2001 From: Chris Chinchilla Date: Mon, 24 Jun 2019 12:40:16 +0200 Subject: [PATCH] Clarify implicit conversion --- docs/types/conversion.rst | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/docs/types/conversion.rst b/docs/types/conversion.rst index 49a3f0100..51e373405 100644 --- a/docs/types/conversion.rst +++ b/docs/types/conversion.rst @@ -8,25 +8,28 @@ Conversions between Elementary Types Implicit Conversions -------------------- -If an operator is applied to different types, the compiler tries to -implicitly convert one of the operands to the type of the other (the same is -true for assignments). In general, an implicit conversion between value-types -is possible if it -makes sense semantically and no information is lost: ``uint8`` is convertible to -``uint16`` and ``int128`` to ``int256``, but ``int8`` is not convertible to ``uint256`` -(because ``uint256`` cannot hold e.g. ``-1``). +If an operator is applied to different types, the compiler tries to implicitly +convert one of the operands to the type of the other (the same is true for assignments). +This means that operations are always performed in the type of one of the operands. +In general, an implicit conversion between value-types is possible if it makes +sense semantically and no information is lost. + +For example, ``uint8`` is convertible to +``uint16`` and ``int128`` to ``int256``, but ``int8`` is not convertible to ``uint256``, +because ``uint256`` cannot hold values such as ``-1``. For more details, please consult the sections about the types themselves. Explicit Conversions -------------------- -If the compiler does not allow implicit conversion but you know what you are -doing, an explicit type conversion is sometimes possible. Note that this may -give you some unexpected behaviour and allows you to bypass some security +If the compiler does not allow implicit conversion but you are confident a conversion will work, +an explicit type conversion is sometimes possible. This may +result in unexpected behaviour and allows you to bypass some security features of the compiler, so be sure to test that the -result is what you want! Take the following example where you are converting -a negative ``int`` to a ``uint``: +result is what you want and expect! + +Take the following example that converts a negative ``int`` to a ``uint``: :: @@ -42,7 +45,7 @@ cut off:: uint32 a = 0x12345678; uint16 b = uint16(a); // b will be 0x5678 now -If an integer is explicitly converted to a larger type, it is padded on the left (i.e. at the higher order end). +If an integer is explicitly converted to a larger type, it is padded on the left (i.e., at the higher order end). The result of the conversion will compare equal to the original integer:: uint16 a = 0x1234;