Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes from Version 1 of NestedFunctionsExample/D2

Show
Ignore:
Author:
Andrej08 (IP: 93.137.24.64)
Timestamp:
09/04/10 21:07:29 (14 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • NestedFunctionsExample/D2

    v0 v1  
     1= Nested Functions = 
     2 
     3''Part of'' TutorialFundamentals 
     4 
     5== Description == 
     6 
     7Nested functions allows you to structure functions in a clever way if that's how your mind works. 
     8 
     9== Example == 
     10 
     11{{{ 
     12#!d 
     13import std.stdio; 
     14 
     15int addSquares(int a, int b) 
     16{ 
     17    int squareIt() 
     18    { 
     19        return (a * a) + (b * b); 
     20    } 
     21     
     22    return squareIt(); 
     23} 
     24 
     25void main()  
     26{ 
     27    writeln(addSquares(2, 2)); 
     28} 
     29}}} 
     30 
     31== How it works == 
     32 
     33The squareIt() function is a nested function inside the addSquares() function. A nested function in D has access to its enclosing function scope, which means it can use any variables declared inside addSquares() as well as its parameters (a special case is when squareIt is defined as a static function, see the static section in the link on the bottom of this page).  
     34 
     35In the '''return squareIt();''' statement, the squareIt() function is evaluated, which in this case gives the result 8. The return statement then returns the value 8 which is used as the argument to the writeln() function. 
     36 
     37 
     38== More Information == 
     39 
     40See also the [http://www.digitalmars.com/d/2.0/function.html#nested D Specification].