diff options
author | chriseth <chris@ethereum.org> | 2018-11-14 02:33:35 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-11-14 02:33:35 +0800 |
commit | 1d4f565a64988a3400847d2655ca24f73f234bc6 (patch) | |
tree | caaa6c26e307513505349b50ca4f2a8a9506752b /docs/control-structures.rst | |
parent | 59dbf8f1085b8b92e8b7eb0ce380cbeb642e97eb (diff) | |
parent | 91b6b8a88e76016e0324036cb7a7f9300a1e2439 (diff) | |
download | dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar.gz dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar.bz2 dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar.lz dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar.xz dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.tar.zst dexon-solidity-1d4f565a64988a3400847d2655ca24f73f234bc6.zip |
Merge pull request #5416 from ethereum/develop
Merge develop into release for 0.5.0
Diffstat (limited to 'docs/control-structures.rst')
-rw-r--r-- | docs/control-structures.rst | 301 |
1 files changed, 136 insertions, 165 deletions
diff --git a/docs/control-structures.rst b/docs/control-structures.rst index 7849d15a..5e3b722b 100644 --- a/docs/control-structures.rst +++ b/docs/control-structures.rst @@ -2,7 +2,7 @@ Expressions and Control Structures ################################## -.. index:: ! parameter, parameter;input, parameter;output +.. index:: ! parameter, parameter;input, parameter;output, parameter;multiple Input Parameters and Output Parameters ====================================== @@ -14,20 +14,26 @@ parameters as output. Input Parameters ---------------- -The input parameters are declared the same way as variables are. As an -exception, unused parameters can omit the variable name. +The input parameters are declared the same way as variables are. +The name of unused parameters can be omitted. For example, suppose we want our contract to accept one kind of external calls with two integers, we would write something like:: - pragma solidity ^0.4.16; + pragma solidity >=0.4.16 <0.6.0; contract Simple { - function taker(uint _a, uint _b) public pure { - // do something with _a and _b. + uint sum; + function taker(uint _a, uint _b) public { + sum = _a + _b; } } +Input parameters can be used just as any other local variable +can be used, they can also be assigned to. + +.. index:: return array, return string, array, string, array of strings, dynamic array, variably sized array, return struct, struct + Output Parameters ----------------- @@ -36,10 +42,10 @@ The output parameters can be declared with the same syntax after the the sum and the product of the two given integers, then we would write:: - pragma solidity ^0.4.16; + pragma solidity >=0.4.16 <0.6.0; contract Simple { - function arithmetics(uint _a, uint _b) + function arithmetic(uint _a, uint _b) public pure returns (uint o_sum, uint o_product) @@ -50,24 +56,29 @@ write:: } The names of output parameters can be omitted. -The output values can also be specified using ``return`` statements. -The ``return`` statements are also capable of returning multiple -values, see :ref:`multi-return`. -Return parameters are initialized to zero; if they are not explicitly -set, they stay to be zero. +The return values can be specified using ``return`` statements, +which are also capable of :ref:`returning multiple values<multi-return>`. +Return parameters can be used as any other local variable and they +are zero-initialized; if they are not explicitly +set, they stay zero. -Input parameters and output parameters can be used as expressions in -the function body. There, they are also usable in the left-hand side -of assignment. + +.. note:: + You cannot return some types from non-internal functions, notably + multi-dimensional dynamic arrays and structs. If you enable the + new experimental ``ABIEncoderV2`` feature by adding ``pragma experimental + ABIEncoderV2;`` to your source file then more types are available, but + ``mapping`` types are still limited to inside a single contract and you + cannot transfer them. .. index:: if, else, while, do/while, for, break, continue, return, switch, goto Control Structures =================== -Most of the control structures from JavaScript are available in Solidity -except for ``switch`` and ``goto``. So -there is: ``if``, ``else``, ``while``, ``do``, ``for``, ``break``, ``continue``, ``return``, ``? :``, with +Most of the control structures known from curly-braces languages are available in Solidity: + +There is: ``if``, ``else``, ``while``, ``do``, ``for``, ``break``, ``continue``, ``return``, with the usual semantics known from C or JavaScript. Parentheses can *not* be omitted for conditionals, but curly brances can be omitted @@ -99,10 +110,10 @@ Internal Function Calls Functions of the current contract can be called directly ("internally"), also recursively, as seen in this nonsensical example:: - pragma solidity ^0.4.16; + pragma solidity >=0.4.16 <0.6.0; contract C { - function g(uint a) public pure returns (uint ret) { return f(); } + function g(uint a) public pure returns (uint ret) { return a + f(); } function f() internal pure returns (uint ret) { return g(7) + f(); } } @@ -111,22 +122,31 @@ the effect that the current memory is not cleared, i.e. passing memory reference to internally-called functions is very efficient. Only functions of the same contract can be called internally. +You should still avoid excessive recursion, as every internal function call +uses up at least one stack slot and there are at most 1024 slots available. + External Function Calls ----------------------- The expressions ``this.g(8);`` and ``c.g(2);`` (where ``c`` is a contract instance) are also valid function calls, but this time, the function will be called "externally", via a message call and not directly via jumps. -Please note that function calls on ``this`` cannot be used in the constructor, as the -actual contract has not been created yet. +Please note that function calls on ``this`` cannot be used in the constructor, +as the actual contract has not been created yet. Functions of other contracts have to be called externally. For an external call, all function arguments have to be copied to memory. -When calling functions of other contracts, the amount of Wei sent with the call and -the gas can be specified with special options ``.value()`` and ``.gas()``, respectively:: +.. note:: + A function call from one contract to another does not create its own transaction, + it is a message call as part of the overall transaction. + +When calling functions of other contracts, you can specify the amount of Wei or gas sent with the call with the special options ``.value()`` and ``.gas()``, respectively. Any Wei you send to the contract is added to the total balance of the contract: - pragma solidity ^0.4.0; + +:: + + pragma solidity >=0.4.0 <0.6.0; contract InfoFeed { function info() public payable returns (uint ret) { return 42; } @@ -134,23 +154,15 @@ the gas can be specified with special options ``.value()`` and ``.gas()``, respe contract Consumer { InfoFeed feed; - function setFeed(address addr) public { feed = InfoFeed(addr); } + function setFeed(InfoFeed addr) public { feed = addr; } function callFeed() public { feed.info.value(10).gas(800)(); } } -The modifier ``payable`` has to be used for ``info``, because otherwise, the `.value()` -option would not be available. +You need to use the modifier ``payable`` with the ``info`` function because +otherwise, the ``.value()`` option would not be available. -Note that the expression ``InfoFeed(addr)`` performs an explicit type conversion stating -that "we know that the type of the contract at the given address is ``InfoFeed``" and -this does not execute a constructor. Explicit type conversions have to be -handled with extreme caution. Never call a function on a contract where you -are not sure about its type. - -We could also have used ``function setFeed(InfoFeed _feed) { feed = _feed; }`` directly. -Be careful about the fact that ``feed.info.value(10).gas(800)`` -only (locally) sets the value and amount of gas sent with the function call and only the -parentheses at the end perform the actual call. +.. warning:: + Be careful that ``feed.info.value(10).gas(800)`` only locally sets the ``value`` and amount of ``gas`` sent with the function call, and the parentheses at the end perform the actual call. So in this case, the function is not called. Function calls cause exceptions if the called contract does not exist (in the sense that the account does not contain code) or if the called contract itself @@ -158,8 +170,8 @@ throws an exception or goes out of gas. .. warning:: Any interaction with another contract imposes a potential danger, especially - if the source code of the contract is not known in advance. The current - contract hands over control to the called contract and that may potentially + if the source code of the contract is not known in advance. The + current contract hands over control to the called contract and that may potentially do just about anything. Even if the called contract inherits from a known parent contract, the inheriting contract is only required to have a correct interface. The implementation of the contract, however, can be completely arbitrary and thus, @@ -174,24 +186,26 @@ throws an exception or goes out of gas. Named Calls and Anonymous Function Parameters --------------------------------------------- -Function call arguments can also be given by name, in any order, +Function call arguments can be given by name, in any order, if they are enclosed in ``{ }`` as can be seen in the following example. The argument list has to coincide by name with the list of parameters from the function declaration, but can be in arbitrary order. :: - pragma solidity ^0.4.0; + pragma solidity >=0.4.0 <0.6.0; contract C { - function f(uint key, uint value) public { - // ... + mapping(uint => uint) data; + + function f() public { + set({value: 2, key: 3}); } - function g() public { - // named arguments - f({value: 2, key: 3}); + function set(uint key, uint value) public { + data[key] = value; } + } Omitted Function Parameter Names @@ -202,7 +216,7 @@ Those parameters will still be present on the stack, but they are inaccessible. :: - pragma solidity ^0.4.16; + pragma solidity >=0.4.16 <0.6.0; contract C { // omitted name for parameter @@ -219,17 +233,17 @@ Those parameters will still be present on the stack, but they are inaccessible. Creating Contracts via ``new`` ============================== -A contract can create a new contract using the ``new`` keyword. The full -code of the contract being created has to be known in advance, so recursive -creation-dependencies are not possible. +A contract can create other contracts using the ``new`` keyword. The full +code of the contract being created has to be known when the creating contract +is compiled so recursive creation-dependencies are not possible. :: - pragma solidity ^0.4.0; + pragma solidity >0.4.99 <0.6.0; contract D { - uint x; - function D(uint a) public payable { + uint public x; + constructor(uint a) public payable { x = a; } } @@ -239,15 +253,17 @@ creation-dependencies are not possible. function createD(uint arg) public { D newD = new D(arg); + newD.x(); } function createAndEndowD(uint arg, uint amount) public payable { // Send ether along with the creation D newD = (new D).value(amount)(arg); + newD.x(); } } -As seen in the example, it is possible to forward Ether while creating +As seen in the example, it is possible to send Ether while creating an instance of ``D`` using the ``.value()`` option, but it is not possible to limit the amount of gas. If the creation fails (due to out-of-stack, not enough balance or other problems), @@ -272,12 +288,15 @@ Assignment Destructuring Assignments and Returning Multiple Values ------------------------------------------------------- -Solidity internally allows tuple types, i.e. a list of objects of potentially different types whose size is a constant at compile-time. Those tuples can be used to return multiple values at the same time. -These can then either be assigned to newly declared variables or to pre-existing variables (or LValues in general): +Solidity internally allows tuple types, i.e. a list of objects of potentially different types whose number is a constant at compile-time. Those tuples can be used to return multiple values at the same time. +These can then either be assigned to newly declared variables or to pre-existing variables (or LValues in general). + +Tuples are not proper types in Solidity, they can only be used to form syntactic +groupings of expressions. :: - pragma solidity >0.4.23 <0.5.0; + pragma solidity >0.4.23 <0.6.0; contract C { uint[] data; @@ -287,29 +306,33 @@ These can then either be assigned to newly declared variables or to pre-existing } function g() public { - // Variables declared with type and assigned from the returned tuple. - (uint x, bool b, uint y) = f(); + // Variables declared with type and assigned from the returned tuple, + // not all elements have to be specified (but the number must match). + (uint x, , uint y) = f(); // Common trick to swap values -- does not work for non-value storage types. (x, y) = (y, x); // Components can be left out (also for variable declarations). - (data.length,,) = f(); // Sets the length to 7 - // Components can only be left out at the left-hand-side of assignments, with - // one exception: - (x,) = (1,); - // (1,) is the only way to specify a 1-component tuple, because (1) is - // equivalent to 1. + (data.length, , ) = f(); // Sets the length to 7 } } +It is not possible to mix variable declarations and non-declaration assignments, +i.e. the following is not valid: ``(x, uint y) = (1, 2);`` + .. note:: - Prior to version 0.4.24 it was possible to assign to tuples of smaller size, either + Prior to version 0.5.0 it was possible to assign to tuples of smaller size, either filling up on the left or on the right side (which ever was empty). This is - now deprecated, both sides have to have the same number of components. + now disallowed, so both sides have to have the same number of components. + +.. warning:: + Be careful when assigning to multiple variables at the same time when + reference types are involved, because it could lead to unexpected + copying behaviour. Complications for Arrays and Structs ------------------------------------ -The semantics of assignment are a bit more complicated for non-value types like arrays and structs. +The semantics of assignments are a bit more complicated for non-value types like arrays and structs. Assigning *to* a state variable always creates an independent copy. On the other hand, assigning to a local variable creates an independent copy only for elementary types, i.e. static types that fit into 32 bytes. If structs or arrays (including ``bytes`` and ``string``) are assigned from a state variable to a local variable, the local variable holds a reference to the original state variable. A second assignment to the local variable does not modify the state but only changes the reference. Assignments to members (or elements) of the local variable *do* change the state. .. index:: ! scoping, declarations, default value @@ -325,101 +348,31 @@ is ``false``. The default value for the ``uint`` or ``int`` types is ``0``. For element will be initialized to the default value corresponding to its type. Finally, for dynamically-sized arrays, ``bytes`` and ``string``, the default value is an empty array or string. -A variable declared anywhere within a function will be in scope for the *entire function*, regardless of where it is declared -(this will change soon, see below). -This happens because Solidity inherits its scoping rules from JavaScript. -This is in contrast to many languages where variables are only scoped where they are declared until the end of the semantic block. -As a result, the following code is illegal and cause the compiler to throw an error, ``Identifier already declared``: - -:: - - // This will not compile - - pragma solidity ^0.4.16; - - contract ScopingErrors { - function scoping() public { - uint i = 0; - - while (i++ < 1) { - uint same1 = 0; - } - - while (i++ < 2) { - uint same1 = 0;// Illegal, second declaration of same1 - } - } - - function minimalScoping() public { - { - uint same2 = 0; - } - - { - uint same2 = 0;// Illegal, second declaration of same2 - } - } - - function forLoopScoping() public { - for (uint same3 = 0; same3 < 1; same3++) { - } - - for (uint same3 = 0; same3 < 1; same3++) {// Illegal, second declaration of same3 - } - } - } - -In addition to this, if a variable is declared, it will be initialized at the beginning of the function to its default value. -As a result, the following code is legal, despite being poorly written: - -:: - - pragma solidity ^0.4.0; - - contract C { - function foo() public pure returns (uint) { - // baz is implicitly initialized as 0 - uint bar = 5; - if (true) { - bar += baz; - } else { - uint baz = 10;// never executes - } - return bar;// returns 5 - } - } - -Scoping starting from Version 0.5.0 ------------------------------------ - -Starting from version 0.5.0, Solidity will change to the more widespread scoping rules of C99 +Scoping in Solidity follows the widespread scoping rules of C99 (and many other languages): Variables are visible from the point right after their declaration -until the end of a ``{ }``-block. As an exception to this rule, variables declared in the +until the end of the smallest ``{ }``-block that contains the declaration. As an exception to this rule, variables declared in the initialization part of a for-loop are only visible until the end of the for-loop. Variables and other items declared outside of a code block, for example functions, contracts, -user-defined types, etc., do not change their scoping behaviour. This means you can +user-defined types, etc., are visible even before they were declared. This means you can use state variables before they are declared and call functions recursively. -These rules are already introduced now as an experimental feature. - As a consequence, the following examples will compile without warnings, since -the two variables have the same name but disjoint scopes. In non-0.5.0-mode, -they have the same scope (the function ``minimalScoping``) and thus it does -not compile there. +the two variables have the same name but disjoint scopes. :: - pragma solidity ^0.4.0; - pragma experimental "v0.5.0"; + pragma solidity >0.4.99 <0.6.0; contract C { function minimalScoping() pure public { { - uint same2 = 0; + uint same; + same = 1; } { - uint same2 = 0; + uint same; + same = 3; } } } @@ -430,8 +383,8 @@ In any case, you will get a warning about the outer variable being shadowed. :: - pragma solidity ^0.4.0; - pragma experimental "v0.5.0"; + pragma solidity >0.4.99 <0.6.0; + // This will report a warning contract C { function f() pure public returns (uint) { uint x = 1; @@ -443,7 +396,26 @@ In any case, you will get a warning about the outer variable being shadowed. } } -.. index:: ! exception, ! throw, ! assert, ! require, ! revert +.. warning:: + Before version 0.5.0 Solidity followed the same scoping rules as JavaScript, that is, a variable declared anywhere within a function would be in scope + for the entire function, regardless where it was declared. The following example shows a code snippet that used + to compile but leads to an error starting from version 0.5.0. + + :: + + pragma solidity >0.4.99 <0.6.0; + // This will not compile + contract C { + function f() pure public returns (uint) { + x = 2; + uint x; + return x; + } + } + +.. index:: ! exception, ! throw, ! assert, ! require, ! revert, ! errors + +.. _assert-and-require: Error handling: Assert, Require, Revert and Exceptions ====================================================== @@ -458,17 +430,17 @@ If used properly, analysis tools can evaluate your contract to identify the cond There are two other ways to trigger exceptions: The ``revert`` function can be used to flag an error and revert the current call. It is possible to provide a string message containing details about the error that will be passed back to the caller. -The deprecated keyword ``throw`` can also be used as an alternative to ``revert()`` (but only without error message). .. note:: - From version 0.4.13 the ``throw`` keyword is deprecated and will be phased out in the future. + There used to be a keyword called ``throw`` with the same semantics as ``revert()`` which + was deprecated in version 0.4.13 and removed in version 0.5.0. When exceptions happen in a sub-call, they "bubble up" (i.e. exceptions are rethrown) automatically. Exceptions to this rule are ``send`` -and the low-level functions ``call``, ``delegatecall`` and ``callcode`` -- those return ``false`` in case +and the low-level functions ``call``, ``delegatecall`` and ``staticcall`` -- those return ``false`` as their first return value in case of an exception instead of "bubbling up". .. warning:: - The low-level ``call``, ``delegatecall`` and ``callcode`` will return success if the called account is non-existent, as part of the design of EVM. Existence must be checked prior to calling if desired. + The low-level functions ``call``, ``delegatecall`` and ``staticcall`` return ``true`` as their first return value if the called account is non-existent, as part of the design of EVM. Existence must be checked prior to calling if desired. Catching exceptions is not yet possible. @@ -478,18 +450,18 @@ a message string for ``require``, but not for ``assert``. :: - pragma solidity ^0.4.22; + pragma solidity >0.4.99 <0.6.0; contract Sharer { - function sendHalf(address addr) public payable returns (uint balance) { + function sendHalf(address payable addr) public payable returns (uint balance) { require(msg.value % 2 == 0, "Even value required."); - uint balanceBeforeTransfer = this.balance; + uint balanceBeforeTransfer = address(this).balance; addr.transfer(msg.value / 2); // Since transfer throws an exception on failure and // cannot call back here, there should be no way for us to // still have half of the money. - assert(this.balance == balanceBeforeTransfer - msg.value / 2); - return this.balance; + assert(address(this).balance == balanceBeforeTransfer - msg.value / 2); + return address(this).balance; } } @@ -505,9 +477,8 @@ An ``assert``-style exception is generated in the following situations: A ``require``-style exception is generated in the following situations: -#. Calling ``throw``. #. Calling ``require`` with an argument that evaluates to ``false``. -#. If you call a function via a message call but it does not finish properly (i.e. it runs out of gas, has no matching function, or throws an exception itself), except when a low level operation ``call``, ``send``, ``delegatecall`` or ``callcode`` is used. The low level operations never throw exceptions but indicate failures by returning ``false``. +#. If you call a function via a message call but it does not finish properly (i.e. it runs out of gas, has no matching function, or throws an exception itself), except when a low level operation ``call``, ``send``, ``delegatecall``, ``callcode`` or ``staticcall`` is used. The low level operations never throw exceptions but indicate failures by returning ``false``. #. If you create a contract using the ``new`` keyword but the contract creation does not finish properly (see above for the definition of "not finish properly"). #. If you perform an external function call targeting a contract that contains no code. #. If your contract receives Ether via a public function without ``payable`` modifier (including the constructor and the fallback function). @@ -525,10 +496,10 @@ The following example shows how an error string can be used together with revert :: - pragma solidity ^0.4.22; + pragma solidity >0.4.99 <0.6.0; contract VendingMachine { - function buy(uint amount) payable { + function buy(uint amount) public payable { if (amount > msg.value / 2 ether) revert("Not enough Ether provided."); // Alternative way to do it: |