aboutsummaryrefslogtreecommitdiffstats
path: root/docs
diff options
context:
space:
mode:
authorchriseth <c@ethdev.com>2016-05-13 05:07:52 +0800
committerchriseth <c@ethdev.com>2016-05-13 05:07:52 +0800
commitc06051d38da28dda515e889fe9f565b8b97a68f5 (patch)
tree2cb607ad544dce918be63860a4157ec7b7e3a9de /docs
parent73ede5bb38e41ec2b96899105ef4a5badcb4be68 (diff)
parent20cec07b466b99893fecfb82a0f0e35acfb6bdda (diff)
downloaddexon-solidity-c06051d38da28dda515e889fe9f565b8b97a68f5.tar.gz
dexon-solidity-c06051d38da28dda515e889fe9f565b8b97a68f5.tar.zst
dexon-solidity-c06051d38da28dda515e889fe9f565b8b97a68f5.zip
Merge pull request #557 from Denton-L/scoping
Added Section about Scoping Behaviours
Diffstat (limited to 'docs')
-rw-r--r--docs/control-structures.rst57
1 files changed, 57 insertions, 0 deletions
diff --git a/docs/control-structures.rst b/docs/control-structures.rst
index 2d959d1d..b24909a6 100644
--- a/docs/control-structures.rst
+++ b/docs/control-structures.rst
@@ -142,6 +142,63 @@ Assigning *to* a state variable always creates an independent copy. On the other
.. index:: ! exception, ! throw
+Scoping and Declarations
+========================
+
+.. index:: ! scoping, ! declarations
+
+In Solidity, a variable declared anywhere within a function will be in scope for the *entire function*, regardless of where it is declared.
+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`::
+
+ contract ScopingErrors {
+ function scoping() {
+ uint i = 0;
+
+ while (i++ < 1) {
+ uint same1 = 0;
+ }
+
+ while (i++ < 2) {
+ uint same1 = 0;// Illegal, second declaration of same1
+ }
+ }
+
+ function minimalScoping() {
+ {
+ uint same2 = 0;
+ }
+
+ {
+ uint same2 = 0;// Illegal, second declaration of same2
+ }
+ }
+
+ function forLoopScoping() {
+ 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::
+
+ function foo() 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
+ }
+
Exceptions
==========