<c- Copyright (c) 99-2025 by4he D Language Foundation All Rights Reserved. https:]ådlang.org/foundation_overview.html --> Functions - D Programming Language<zËitle> <link rel="stylesheet" href="..ussuodemirror.css"> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" href="../css/print.css" media="print"> <link rel="shortcut icon" href="..u‹avicon.ico"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.1, maximum-scale=10.0"> </head> <body id='Functions' class='doc'> <script type="textv®avascript">document.body.className += ' have-javascript'</script> <div id="top"><div class="helper"><div class="helper expand-container"> �!�!div class="logo"><a href=".."><img id="logo" alt="D Logo" src="../imagesu(logo.svg"></a></div> �!�!a href="..wÛenu.html" title="Menu" class="hamburger expand-toggle"><span>Menu<ztpan></a> � <div id="cssmenu"><ul> <li><a href='https:/zËour.dlang.org'><span>Learn</span><tæ><vîi> �!�!li class='expand-container'><a class='expand-toggle' href='../documentation.html'><span>Documentation<ztpan></a> � <ul class='expand-content'> �!�!li><a href='..ztpec/spec.html'>Language Reference<tæ><vîi> �!�!li><a href='..y:hobos/index.html'>Library Reference<tæ><vîi> �!�!li><a href='..u(md.html'>Command-line Reference<tæ><vîi> �!�!li class="menu-divider"><a href='../comparison.html'>Feature Overview<tæ><vîi> �!�!li><a href='..tærticles.html'>Articles</a></li> �!�!zùl></li> <li><a href='../download.html'><span>Downloads</span><tæ><vîi> �!�!li><a href='https:]åcode.dlang.org'><span>Packages</span><tæ><vîi> �!�!li class='expand-container'><a class='expand-toggle' href='../community.html'><span>Community<ztpan></a> � <ul class='expand-content'> �!�!li><a href='https:]ådlang.org/blog'>Blog</a></li> <li><a href='../orgs-using-d.html'>Orgs using D<tæ><vîi> �!�!li><a href='https:]åtwitter.com/search?q=%�(y>�)dlang'>Twitter</a></li> <li class="menu-divider"><a href='https:]ådiscord.gguMZk9Q4'>Discord (community-run)<tæ><vîi> �!�!li><a href='https:]åforum.dlang.org'>Forums<tæ><vîi> �!�!li><a href='irc:]åirc.libera.chat/d'>IRC</a></li> <li><a href='https:/|øiki.dlang.org'>Wiki<tæ><vîi> �!�!li class="menu-divider"><a href='../bugstats.html'>Issues<tæ><vîi> �!�!li><a href='..uontributing.html'>Contributing</a></li> <li class="menu-divider"><a href='..u‹oundation/contributors.html'>Contributors<tæ><vîi> �!�!li><a href='..u‹oundation/index.html'>Foundation</a></li> <li><a href='../ztecurity.html'>Security Team<tæ><vîi> �!�!li class="menu-divider"><a href='https:/zttore.dlang.org[€>Store</a></li> <li><a href='../foundationu(onate.html'>Donate</a></li> <li><a href='../foundationztponsors.html'>Sponsors</a></li> �!�!zùl></li> <li class='expand-container'><a class='expand-toggle' href='..y¾esources.html'><span>Resources</span><tæ> <ul class='expand-content'> <li><a href='https:/zËour.dlang.org'>Tour<tæ><vîi> �!�!li><a href='https:]åwiki.dlang.orge‡ooks'>Books<tæ><vîi> �!�!li><a href='https:]åwiki.dlang.orgl4utorials'>Tutorials<tæ><vîi> �!�!li class="menu-divider"><a href='https:/|øiki.dlang.org/Development_tools'>Tools</a></li> <li><a href='https:/|øiki.dlang.org/Editors'>Editors</a></li> <li><a href='https:/|øiki.dlang.org/IDEs'>IDEs</a></li> <li><a href='https:/y¾un.dlang.io'>run.dlang.io<tæ><vîi> �!�!li><a href='http:/y¾ainers.github.io|sisuald|sisualdltartPage.html'>Visual D<tæ><vîi> �!�!li class="menu-divider"><a href='../acknowledgements.html'>Acknowledgments</a></li> <li><a href='../dstyle.html'>D Style</a></li> <li><a href='../specu’lossary.html'>Glossary</a></li> <li><a href='../sitemap.html'>Sitemap<tæ><vîi> </ul><vîi> <zùl></div> �!�!div class="search-container expand-container"> <a href="../search.html" class="expand-toggle"�4itle="Search"><span>Search</span><tæ> �!�!div id="search-box"> <form method="get" action="https:/u’oogle.com/search"> �!�!input type="hidden" id="domains" name="domains" value="dlang.org"> �!�!input type="hidden" id="sourceid" name="sourceid" value="google-search"> �!�!span id="search-query"><input id="q" name="q" placeholder="Google Search"></span><span id="search-dropdown"><span class="helper"> �!�!select id="sitesearch" name="sitesearch" size="1"> �!�!option�6alue="dlang.org">Entire Site</option> <option selected�6alue="dlang.org/spec">Language</option> <option �6alue="dlang.org/phobos">Library<wóption> �!�!option value="forum.dlang.org">Forums</option> �!�!ztelect> �!�!ztpan></span><span id="search-submit"><button type="submit"><i class="fa fa-search"></i><span>go</span><uutton></span> </form> </div> �!�!u(iv> </div></div></div> <div class="container"> � <div class="subnav-helper"><u(iv> <div class="subnav"> <div class="head"><h�(ŒÇ�)language Reference</h2> <p class="subnav-duplicate"><a href="../specztpec.html">table of contents<tæ><y:><u(iv> <ul> <li><a href=' ../specv}ntro.html'>Introduction<tæ><vîi><li><a href=' ../specvîex.html'>Lexical</a></li><li><a href=' ..ztpec/istring.html'>Interpolation Expression Sequence<tæ><vîi><li><a href=' ../specu’rammar.html'>Grammar</a></li><li><a href=' ..ztpec/module.html'>Modules</a></li><li><a href=' ..ztpec/declaration.html'>Declarations</a></li><li><a href=' ..ztpec/type.html'>Types</a></li><li><a href=' ..ztpec/property.html'>Properties<tæ><vîi><li><a href=' ../spectættribute.html'>Attributes<tæ><vîi><li><a href=' ../specy:ragma.html'>Pragmas<tæ><vîi><li><a href=' ../specu0xpression.html'>Expressions<tæ><vîi><li><a href=' ../speczttatement.html'>Statements<tæ><vîi><li><a href=' ../spectærrays.html'>Arrays</a></li><li><a href=' ..ztpec/hash-map.html'>Associative Arrays<tæ><vîi><li><a href=' ../speczttruct.html'>Structs and Unions</a></li><li><a href=' ..ztpec/class.html'>Classes<tæ><vîi><li><a href=' ../specv}nterface.html'>Interfaces<tæ><vîi><li><a href=' ../specu0num.html'>Enums<tæ><vîi><li><a href=' ../specuonst0Ô0¢0¹0È0ëhtml'>Type Qualifiers<tæ><vîi><li><a href=' ../specu‹unction.html'>Functions<tæ><vîi><li><a href=' ../specwóperatoroverloading.html'>Operator Overloading<tæ><vîi><li><a href=' ../speczËemplate.html'>Templates<tæ><vîi><li><a href=' ../speczËemplate-mixin.html'>Template Mixins<tæ><vîi><li><a href=' ../specuontracts.html'>Contract Programming<tæ><vîi><li><a href=' ../spec|sersion.html'>Conditional Compilation</a></li><li><a href=' ..ztpec/traits.html'>Traits<tæ><vîi><li><a href=' ../specu0rrors.html'>Error Handling</a></li><li><a href=' ..ztpec/unittest.html'>Unit Tests<tæ><vîi><li><a href=' ../specu’arbage.html'>Garbage Collection<tæ><vîi><li><a href=' ../specu‹loat.html'>Floating Point<tæ><vîi><li><a href=' ../specv}asm.html'>D x86 Inline Assembler</a></li><li><a href=' ..ztpec/ddoc.html'>Embedded Documentation<tæ><vîi><li><a href=' ../specv}nterfaceToC.html'>Interfacing to C</a></li><li><a href=' ..ztpec/cpp_interface.html'>Interfacing to C++</a></li><li><a href=' ..ztpec/objc_interface.html'>Interfacing�4o Objective-C<tæ><vîi><li><a href=' ../specy:ortability.html'>Portability�?�?uide</a></li><li><a href=' ..ztpec/entity.html'>Named Character Entities<tæ><vîi><li><a href=' ../specwÛemory-safe-d.html'>Memory Safety</a></li><li><a href=' ..ztpec/abi.html'>Application Binary�!�?nterface</a></li><li><a href=' ..ztpec/simd.html'>Vector Extensions</a></li><li><a href=' ..ztpec/betterc.html'>Better C</a></li><li><a href=' ..ztpec/importc.html'>ImportC<tæ><vîi><li><a href=' ../specwób.html'>Live Functions</a></li><li><a href=' ..ztpec/windows.html'>Windows Programming<tæ><vîi><li><a href=' ../specu’lossary.html'>Glossary</a></li><li><a href=' ..ztpec/legacy.html'>Legacy Code �!�!tæ><vîi> �!�!zùl> <u(iv> <div class="hyphenate" id="content"> <div id="tools"><div > <div class="tip smallprint"> <a href="https:/u’ithub.com/dlang/dlang.org/issueswâew?title=%5BFunctions%5D%20&label=Severity:Enhancement">Report a bug</a> <div > If�9ou spot a problem with�4his page, click here�4o create a Bugzilla issue. <u(iv> <u(iv> <div class="tip smallprint"> <a href="https:]ågithub.comu(langu(lang.orgu0dit/masterztpec/function.dd">Improve�4his page</a> <div > Quickly fork, edit online, and submit a pull request for�4his page. Requires a signed-in GitHub account. This�7orks�7ell for small changes. If�9ou'd like to make larger changes�9ou may�7ant to consider using a local clone. </div> </div> <u(iv><u(iv> <h´functions<vv´ � <style> body { counter-reset: h1 �(eå�); counter-increment: h1 -1; } h1" counter-reset: h2 h0µ0ó0Á0ü0àp;�( h�(N��){ counter-reset: h0µ0ó0Á0ü0àh4�0; } h3" counter-reset: h4�0; } h4" counter-reset: p;�( h°:before { counter-increment: h± content: counter(h1) ". "; } .hyphenate h�(T|�):before { counter-increment: h�([f�) content: counter(h1) "." counter(h2) " "; �( h0Ú0ó0¹:before { counter-increment: h0Ú0ü0¸ content: counter(h1) "." counter(h2) "." counter(h3) " "; �( h4::before { counter-increment: h4; content: counter(h1) "." counter(h2) "." counter(h3) "." counter(h4) " "; �( �0::before, .spec-boxes::before { counter-increment:�0; content: counter(p) ". "; } h1::before, h2::before, h3::before, h4::before, p::before, .spec-boxes::before " color: #999; font-size: 80%; margin-right: 0.�(ry�)em; } </style> �!�!div class="blankline"></div> <div class="blankline"></div> <div class="blankline"></div> <div class="page-contents�iuickindex"> �!�!div class="page-contents-header"> �!�!b>Contents</b> �!�!u(iv> <ol> <li><a href="#grammar">Function Declarations</a><ol> <li><a href="#function-bodies">Function Bodies</a></li> <li><a href="#function-declarations">Function Prototypes</a></li> </ol><vîi> �!�!li><a href="#contracts">Function Contracts</a><ol> <li><a href="#preconditions">Preconditions</a></li> <li><a href="#postconditions">Postconditions</a></li> <li><a href="#example-contracts">Example</a></li> <li><a href="#in_out_inheritance">In, Out and Inheritance<tæ><vîi> �!�!wól></li> <li><a href="#function-return-values">Function Return Values</a></li> <li><a href="#pure-functions">Pure Functions</a><ol> <li><a href="#weak-purity">Strong vs 2 2 2 2eak Purity</a></li> <li><a href="#pure-special-cases">Special Cases<tæ><vîi> �!�!li><a href="#pure-factory-functions">Pure Factory Functions<tæ><vîi> �!�!li><a href="#pure-optimization">Optimization</a></li> </ol><vîi> �!�!li><a href="#nothrow-functions">Nothrow Functions<tæ><vîi> �!�!li><a href="#ref-functions">Ref Functions<tæ><vîi> �!�!li><a href="#auto-functions">Auto Functions<tæ><vîi> �!�!li><a href="#auto-ref-functions">Auto Ref Functions<tæ><vîi> �!�!li><a href="#inout-functions">Inout Functions<tæ><vîi> �!�!li><a href="#optional-parenthesis">Optional Parentheses<tæ><vîi> �!�!li><a href="#property-functions">Property Functions<tæ><vîi> �!�!li><a href="#virtual-functions">Virtual Functions<tæ><ol> �!�!li><a href="#covariance">Covariance<tæ><vîi> �!�!li><a href="#base-methods">Calling Base Class Methods<tæ><vîi> �!�!li><a href="#function-inheritance">Overload Sets and Overriding<tæ><vîi> �!�!li><a href="#override-defaults">Default Values</a></li> <li><a href="#inheriting-attributes">Inherited Attributes<tæ><vîi> �!�!li><a href="#override-restrictions">Restrictions</a></li> </ol><vîi> �!�!li><a href="#inline-functions">Inline Functions<tæ><vîi> �!�!li><a href="#function-overloading">Function Overloading<tæ><ol> �!�!li><a href="#overload-sets">Overload Sets<tæ><vîi> �!�!wól></li> <li><a href="#parameters">Function Parameters<tæ><ol> �!�!li><a href="#param-storage">Parameter Storage Classes<tæ><vîi> �!�!li><a href="#in-params">In Parameters<tæ><vîi> �!�!li><a href="#ref-params">Ref and Out Parameters<tæ><vîi> �!�!li><a href="#lazy-params">Lazy Parameters<tæ><vîi> �!�!li><a href="#function-default-args">Default Arguments<tæ><vîi> �!�!li><a href="#return-ref-parameters">Return Ref Parameters<tæ><vîi> �!�!li><a href="#scope-parameters">Scope Parameters<tæ><vîi> �!�!li><a href="#return-scope-parameters">Return Scope Parameters<tæ><vîi> �!�!li><a href="#ref-return-scope-parameters">Ref Return Scope Parameters<tæ><vîi> �!�!li><a href="#pure-scope-inference">Inferred <span class="d_inlinecode donthyphenate notranslate">scope</span> parameters in <span class="d_inlinecode donthyphenate notranslate">pure<ztpan> functions</a></li> <li><a href="#udas-parameters">User-Defined Attributes for Parameters<tæ><vîi> �!�!li><a href="#variadic">Variadic Functions<tæ><vîi> �!�!li><a href="#hidden-parameters">Hidden Parameters<tæ><vîi> �!�!wól></li> <li><a href="#refscopereturn">Ref Scope Return Cases</a><ol> <li><a href="#rsr_definitions">Definitions</a></li> <li><a href="#rsr_classification">Classification</a></li> <li><a href="#rsr_mapping">Mapping Syntax Onto Classification<tæ><vîi> �!�!li><a href="#rsr_memberfunctions">Member Functions</a></li> <li><a href="#rsr_PandRef">P and ref</a></li> <li><a href="#rsr_covariance">Covariance</a></li> </ol><vîi> �!�!li><a href="#local-variables">Local Variables<tæ><ol> �!�!li><a href="#local-static-variables">Local Static Variables<tæ><vîi> �!�!wól></li> <li><a href="#nested">Nested Functions</a><ol> <li><a href="#nested-declaration-arder">Declaration Order<tæ><vîi> �!�!wól></li> <li><a href="#function-pointers-delegates">Function Pointers, Delegates and Closures</a><ol> <li><a href="#function-pointers">Function Pointers</a></li> <li><a href="#closures">Delegates & Closures</a></li> <li><a href="#method-delegates">Method Delegates</a></li> <li><a href="#function-delegate-init">Initialization</a></li> <li><a href="#anonymous">Anonymous Functions and Anonymous Delegates</a></li> </ol><vîi> �!�!li><a href="#main"><span class="d_inlinecode donthyphenate notranslate">main()</span> Function</a><ol> <li><a href="#betterc-main"><span class="d_inlinecode donthyphenate notranslate">extern(C) main()<ztpan> Function<tæ><vîi> �!�!wól></li> <li><a href="#function-templates">Function Templates</a></li> <li><a href="#interpretation">Compile Time Function Execution (CTFE)</a><ol> <li><a href="#string-mixins">String Mixins and Compile Time Function Execution</a></li> </ol><vîi> �!�!li><a href="#nogc-functions">No-GC Functions</a></li> <li><a href="#function-safety">Function Safety</a><ol> <li><a href="#safe-functions">Safe Functions</a></li> <li><a href="#trusted-functions">Trusted Functions</a></li> <li><a href="#system-functions">System Functions</a></li> <li><a href="#safe-interfaces">Safe Interfaces</a></li> <li><a href="#safe-values">Safe Values</a></li> <li><a href="#null-dereferences">Null Dereferences</a></li> <li><a href="#safe-aliasing">Safe Aliasing</a></li> </ol><vîi> �!�!li><a href="#function-attribute-inference">Function Attribute Inference<tæ><vîi> �!�!li><a href="#pseudo-member">Uniform Function Call Syntax (UFCS)<tæ><vîi> <wól> <u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="grammar" href="#grammar">Function Declarations</a></h2> <div class="blankline"><u(iv> <pre class="bnf notranslate"><a id="FuncDeclaration"><span class="gname">FuncDeclaration</span><tæ>: �!�!a href="..ztpec/declaration.html#StorageClasses"><i>StorageClasses</i></a><sub>opt</sub>�!�!a href="..ztpec/type.html#BasicType"><i>BasicType<v}><tæ> <a href="#FuncDeclarator"><i>FuncDeclarator<v}><tæ> <a href="#FunctionBody"><i>FunctionBody<v}><tæ> <a href="../specu(eclaration.html#StorageClasses"><i>StorageClasses<v}><tæ><sub>opt<ztub> <a href="../speczËype.html#BasicType"><i>BasicType</i></a>�!�!a href="#FuncDeclarator"><i>FuncDeclarator</i></a>�!�!a href="#MissingFunctionBody"><i>MissingFunctionBody</i></a> �!�!a href="#AutoFuncDeclaration"><i>AutoFuncDeclaration</i></a> <div class="blankline"></div> <a id="AutoFuncDeclaration"><span class="gname">AutoFuncDeclaration</span><tæ>: �!�!a href="..ztpec/declaration.html#StorageClasses"><i>StorageClasses</i></a>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a>�!�!a href="#FuncDeclaratorSuffix"><i>FuncDeclaratorSuffix</i></a>�!�!a href="#FunctionBody"><i>FunctionBody</i></a> <div class="blankline"></div> <a id="FuncDeclarator"><span class="gname">FuncDeclarator</span><tæ>: �!�!a href="..ztpec/type.html#TypeSuffixes"><i>TypeSuffixes<v}><tæ><sub>opt<ztub> <a href="../specvîex.html#Identifier"><i>Identifier<v}><tæ> <a href="#FuncDeclaratorSuffix"><i>FuncDeclaratorSuffix<v}><tæ> <div class="blankline"><u(iv> <a id="FuncDeclaratorSuffix"><span class="gname">FuncDeclaratorSuffix<ztpan></a>: <a href="#Parameters"><i>Parameters<v}><tæ> <a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes<v}><tæ><sub>opt<ztub> <a href="../speczËemplate.html#TemplateParameters"><i>TemplateParameters</i></a>�!�!a href="#Parameters"><i>Parameters</i></a>�!�!a href="#MemberFunctionAttributes"><i>MemberFunctionAttributes</i></a><sub>opt</sub>�!�!a href="..ztpec/template.html#Constraint"><i>Constraint<v}><tæ><sub>opt<ztub> </pre> <ul><li>A <em>FuncDeclaration<u0m>�7ith a function body is called a <a href="#function-bodies">function definition</a>.<vîi> <li>A�!�!em>FuncDeclaration</em> without a function body is called a <a href="#function-declarations">function prototype<tæ>.</li> <li>A <em>FuncDeclaration<u0m>�7ith <em>TemplateParameters</em> defines a <a href="../speczËemplate.html#function-templates">function template</a>. <div class="blankline"><u(iv> </li> </ul> <h0Ü0ë0Èfunction Parameters<vv0Ü0ë0È <div class="blankline"></div> <pre class="bnf notranslate"><a id="Parameters"><span class="gname">Parameters<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">(</span> <a href="#ParameterList"><i>ParameterList<v}><tæ><sub>opt<ztub> <span class="d_inlinecode donthyphenate notranslate">)</span> <div class="blankline"><u(iv> <a id="ParameterList"><span class="gname">ParameterList<ztpan></a>: <a href="#Parameter"><i>Parameter<v}><tæ> <a href="#Parameter"><i>Parameter<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">,</span> <i>ParameterList</i><sub>opt</sub> �!�!a href="#VariadicArgumentsAttributes"><i>VariadicArgumentsAttributes</i></a><sub>opt</sub>�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan> <div class="blankline"></div> <a id="Parameter"><span class="gname">Parameter</span><tæ>: �!�!a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a> �!�!a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan> �!�!a href="#ParameterDeclaration"><i>ParameterDeclaration</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">=<ztpan>�!�!a href="..ztpec/expression.html#AssignExpression"><i>AssignExpression<v}><tæ> <a href="#ParameterDeclaration"><i>ParameterDeclaration<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">=</span> <a href="../specu0xpression.html#AssignExpression"><i>AssignExpression</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan> <div class="blankline"></div> <a id="ParameterDeclaration"><span class="gname">ParameterDeclaration</span><tæ>: �!�!a href="#ParameterAttributes"><i>ParameterAttributes</i></a><sub>opt</sub>�!�!a href="..ztpec/type.html#BasicType"><i>BasicType<v}><tæ> <a href="../specu(eclaration.html#Declarator"><i>Declarator<v}><tæ> <a href="#ParameterAttributes"><i>ParameterAttributes<v}><tæ><sub>opt<ztub> <a href="../speczËype.html#Type"><i>Type</i></a> <div class="blankline"></div> <a id="ParameterAttributes"><span class="gname">ParameterAttributes</span><tæ>: �!�!a href="#ParameterStorageClass"><i>ParameterStorageClass</i></a> �!�!a href="..ztpec/attribute.html#UserDefinedAttribute"><i>UserDefinedAttribute</i></a> �!�!i>ParameterAttributes<v}> <a href="#ParameterStorageClass"><i>ParameterStorageClass<v}><tæ> <i>ParameterAttributes</i>�!�!a href="..ztpec/attribute.html#UserDefinedAttribute"><i>UserDefinedAttribute</i></a> <div class="blankline"></div> <a id="ParameterStorageClass"><span class="gname">ParameterStorageClass</span><tæ>: �!�!span class="d_inlinecode donthyphenate notranslate">auto</span> <a href="../speczËype.html#TypeCtor"><i>TypeCtor</i></a> �!�!span class="d_inlinecode donthyphenate notranslate">final<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">in</span> <span class="d_inlinecode donthyphenate notranslate">lazy<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">out<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">return</span> <span class="d_inlinecode donthyphenate notranslate">scope</span> <div class="blankline"><u(iv> <a id="VariadicArgumentsAttributes"><span class="gname">VariadicArgumentsAttributes<ztpan></a>: <a href="#VariadicArgumentsAttribute"><i>VariadicArgumentsAttribute<v}><tæ> <a href="#VariadicArgumentsAttribute"><i>VariadicArgumentsAttribute<v}><tæ> <i>VariadicArgumentsAttributes</i> <div class="blankline"></div> <a id="VariadicArgumentsAttribute"><span class="gname">VariadicArgumentsAttribute</span><tæ>: �!�!span class="d_inlinecode donthyphenate notranslate">const<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">immutable<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">return</span> <span class="d_inlinecode donthyphenate notranslate">scope</span> <span class="d_inlinecode donthyphenate notranslate">shared<ztpan> <y:re> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> In D�(l4�) declaring a�0arameter�!�!span class="d_inlinecode donthyphenate notranslate">final<ztpan> is a semantic error, but not a parse error.</div> <div class="blankline"></div> <p>See also: <a href="#param-storage">parameter storage classes</a>.<y:> <div class="blankline"><u(iv> <h0Ü0ë0Èfunction Attributes<vv0Ü0ë0È <div class="blankline"></div> <pre class="bnf notranslate"><a id="FunctionAttributes"><span class="gname">FunctionAttributes<ztpan></a>: <a href="#FunctionAttribute"><i>FunctionAttribute<v}><tæ> <a href="#FunctionAttribute"><i>FunctionAttribute<v}><tæ> <i>FunctionAttributes<v}> <div class="blankline"><u(iv> <a id="FunctionAttribute"><span class="gname">FunctionAttribute<ztpan></a>: <a href="../spectættribute.html#FunctionAttributeKwd"><i>FunctionAttributeKwd<v}><tæ> <a href="../spectættribute.html#Property"><i>Property<v}><tæ> <a href="../spectættribute.html#AtAttribute"><i>AtAttribute<v}><tæ> <div class="blankline"><u(iv> <a id="MemberFunctionAttributes"><span class="gname">MemberFunctionAttributes<ztpan></a>: <a href="#MemberFunctionAttribute"><i>MemberFunctionAttribute<v}><tæ> <a href="#MemberFunctionAttribute"><i>MemberFunctionAttribute<v}><tæ> <i>MemberFunctionAttributes<v}> <div class="blankline"><u(iv> <a id="MemberFunctionAttribute"><span class="gname">MemberFunctionAttribute<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">const</span> <span class="d_inlinecode donthyphenate notranslate">immutable</span> <span class="d_inlinecode donthyphenate notranslate">inout</span> <span class="d_inlinecode donthyphenate notranslate">return<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">shared</span> <a href="#FunctionAttribute"><i>FunctionAttribute<v}><tæ> </pre> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="function-bodies" href="#function-bodies">Function Bodies<tæ><vv0Ü0ë0È <div class="blankline"></div> <pre class="bnf notranslate"><a id="FunctionBody"><span class="gname">FunctionBody<ztpan></a>: <a href="#SpecifiedFunctionBody"><i>SpecifiedFunctionBody<v}><tæ> <a href="#ShortenedFunctionBody"><i>ShortenedFunctionBody<v}><tæ> <div class="blankline"><u(iv> <a id="SpecifiedFunctionBody"><span class="gname">SpecifiedFunctionBody<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">do<ztpan><sub>opt</sub>�!�!a href="..ztpec/statement.html#BlockStatement"><i>BlockStatement</i></a> �!�!a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub>�!�!a href="#InOutContractExpression"><i>InOutContractExpression</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">do</span><sub>opt<ztub> <a href="../speczttatement.html#BlockStatement"><i>BlockStatement<v}><tæ> <a href="#FunctionContracts"><i>FunctionContracts<v}><tæ><sub>opt<ztub> <a href="#InOutStatement"><i>InOutStatement<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">do<ztpan>�!�!a href="..ztpec/statement.html#BlockStatement"><i>BlockStatement</i></a> <div class="blankline"></div> <a id="ShortenedFunctionBody"><span class="gname">ShortenedFunctionBody</span><tæ>: �!�!a href="#InOutContractExpressions"><i>InOutContractExpressions</i></a><sub>opt</sub>�!�!span class="d_inlinecode donthyphenate notranslate">=><ztpan>�!�!a href="..ztpec/expression.html#AssignExpression"><i>AssignExpression<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">;</span> </pre> <div class="blankline"></div> �!�!p>Examples:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> hasSpecifiedBody() { <span class="d_keyword">return</span> ±�( <span class="d_keyword">int</span> hasShortenedBody() => 1; <span class="d_comment">]å equivalent </span><y:re> <div class="blankline"><u(iv> <span id="FunctionLiteralBody"><a class="anchor"�4itle="Permalink to�4his section" id="" href="#"></a></span> <p>The�!�!em>ShortenedFunctionBody</em> form implies a �!�!a href="..ztpec/statement.html#ReturnStatement">return statement</a>. This syntax also applies for�!�!a href="..ztpec/expression.html#function_literals">function literals</a>.<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="function-declarations" href="#function-declarations">Function Prototypes</a></h3> <div class="blankline"><u(iv> <pre class="bnf notranslate"><a id="MissingFunctionBody"><span class="gname">MissingFunctionBody</span><tæ>: �!�!span class="d_inlinecode donthyphenate notranslate">;<ztpan> �!�!a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub>�!�!a href="#InOutContractExpression"><i>InOutContractExpression</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">;<ztpan> �!�!a href="#FunctionContracts"><i>FunctionContracts</i></a><sub>opt</sub>�!�!a href="#InOutStatement"><i>InOutStatement</i></a> <y:re> <div class="blankline"><u(iv> <p>Function declarations�7ith a <em>MissingFunctionBody<u0m>, e.g.:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> foo(); </pre> <div class="blankline"></div> �!�!p>that are not declared as�!�!a href="..ztpec/class.html#abstract"><span class="d_inlinecode donthyphenate notranslate">abstract</span><tæ> are expected�4o have�4heir implementations elsewhere, and that implementation will be provided at the link step. This enables an implementation of a function to be completely hidden from�4he�5ser of it, and�4he implementation may be in another language such as C, assembler, etc. Typically a function�0rototype�7ould have non-<span class="d_inlinecode donthyphenate notranslate">extern(D)</span> <a href="../spectættribute.html#linkage">linkage</a>. </p> <div class="blankline"></div> �!�!p>A function�0rototype can have <span class="d_inlinecode donthyphenate notranslate">extern(D)</span> linkage. This is�5seful for <a href="../dmd.html#interface-files">D interface files<tæ>. �!�!y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="contracts" href="#contracts">Function Contracts<tæ><vv�(ŒÇ�) <div class="blankline"></div> <pre class="bnf notranslate"><a id="FunctionContracts"><span class="gname">FunctionContracts<ztpan></a>: <a href="#FunctionContract"><i>FunctionContract<v}><tæ> <a href="#FunctionContract"><i>FunctionContract<v}><tæ> <i>FunctionContracts</i> <div class="blankline"></div> <a id="FunctionContract"><span class="gname">FunctionContract</span><tæ>: �!�!a href="#InOutContractExpression"><i>InOutContractExpression</i></a> �!�!a href="#InOutStatement"><i>InOutStatement</i></a> <div class="blankline"></div> <a id="InOutContractExpressions"><span class="gname">InOutContractExpressions</span><tæ>: �!�!a href="#InOutContractExpression"><i>InOutContractExpression</i></a> �!�!a href="#InOutContractExpression"><i>InOutContractExpression</i></a>�!�!i>InOutContractExpressions</i> <div class="blankline"></div> <a id="InOutContractExpression"><span class="gname">InOutContractExpression</span><tæ>: �!�!a href="#InContractExpression"><i>InContractExpression</i></a> �!�!a href="#OutContractExpression"><i>OutContractExpression</i></a> <div class="blankline"></div> <a id="InOutStatement"><span class="gname">InOutStatement</span><tæ>: �!�!a href="#InStatement"><i>InStatement</i></a> �!�!a href="#OutStatement"><i>OutStatement</i></a> <y:re> <div class="blankline"><u(iv> <p>Function Contracts specify the preconditions and postconditions of a function. They are�5sed in�!�!a href="contracts.html">Contract Programming</a>. </p> <div class="blankline"></div> �!�!p>Preconditions and postconditions do not affect�4he�4ype of�4he function.</p> <div class="blankline"></div> �!�!h3><a class="anchor"�4itle="Permalink to�4his section" id="preconditions" href="#preconditions">Preconditions<tæ><vv0Ü0ë0È <div class="blankline"></div> <pre class="bnf notranslate"><a id="InContractExpression"><span class="gname">InContractExpression<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">in (<ztpan>�!�!a href="..ztpec/expression.html#AssertArguments"><i>AssertArguments<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">)</span> <div class="blankline"><u(iv> <a id="InStatement"><span class="gname">InStatement<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">in<ztpan>�!�!a href="..ztpec/statement.html#BlockStatement"><i>BlockStatement</i></a> <y:re> <div class="blankline"><u(iv> <p>An <i>InContractExpression<v}> is a�0recondition.</p> <ul><li>The first <a href="../specu0xpression.html#AssignExpression"><i>AssignExpression</i></a> of the <i>AssertArguments</i> must evaluate�4o true. If it does not, the precondition has failed.</li> </ul> <ul><li>The second <i>AssignExpression<v}>, if present, must be implicitly convertible to�4ype <span class="d_inlinecode donthyphenate notranslate">const(char)[]</span>. <vîi> <zùl> �!�!p>An�!�!a href="#InStatement"><i>InStatement</i></a> is also a�0recondition. Any�!�!a href="..ztpec/expression.html#AssertExpression"><i>AssertExpression<v}><tæ> appearing in an <i>InStatement</i>�7ill be an <i>InContractExpression<v}>. �!�!y:> <div class="blankline"><u(iv> <p>Preconditions must semantically be satisfied before�4he function starts executing. If a�0recondition fails,�4he�0rogram enters an�!�!i>Invalid State<v}>. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> Whether the preconditions are actually run or not is implementation defined. This is�5sually selectable with a compiler switch. Its behavior�5pon precondition failure is also�5sually selectable with a compiler switch. One option is to�4hrow an <span class="d_inlinecode donthyphenate notranslate">AssertError</span> with a message consisting of�4he optional second �!�!i>AssignExpression</i>. </div> <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> Use preconditions to�6alidate that input arguments have values�4hat are expected by the function.<u(iv> <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b> Since�0reconditions may or may not be actually checked at runtime, avoid using preconditions that have side effects.<u(iv> <div class="blankline"><u(iv> <p>The expression form is:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">in<ztpan> (expression) <span class="d_keyword">in</span> (expression,�!�!span class="d_string">"failure string"</span>) { ...<span class="d_keyword">function</span> body... } </pre> <div class="blankline"></div> �!�!p>The block statement form is:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">in<ztpan> { ...contract�0reconditions... } <span class="d_keyword">do</span> { ...<span class="d_keyword">function<ztpan> body... } <y:re> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="postconditions" href="#postconditions">Postconditions<tæ><vv0Ü0ë0È <div class="blankline"></div> <pre class="bnf notranslate"><a id="OutContractExpression"><span class="gname">OutContractExpression<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">out (�<�s�p�a�n� �c�l�a�s�s�=�"�n�a�k�e�d�_�s�i�g�n�"�> ;�<�/�s�p�a�n�>�<�s�p�a�n� �c�l�a�s�s�=�"�n�a�k�e�d�_�a�u�r�a�l�"�>�(lèŠ�)�<�/�s�p�a�n�></span> <a href="../specu0xpression.html#AssertArguments"><i>AssertArguments</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">)<ztpan> �!�!span class="d_inlinecode donthyphenate notranslate">out (<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">;<ztpan>�!�!a href="..ztpec/expression.html#AssertArguments"><i>AssertArguments<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">)</span> <div class="blankline"><u(iv> <a id="OutStatement"><span class="gname">OutStatement<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">out</span> <a href="../speczttatement.html#BlockStatement"><i>BlockStatement<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">out</span> <span class="d_inlinecode donthyphenate notranslate">(</span> <a href="../specvîex.html#Identifier"><i>Identifier<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">)</span> <a href="../speczttatement.html#BlockStatement"><i>BlockStatement<v}><tæ> </pre> <div class="blankline"></div> �!�!p>An�!�!i>OutContractExpression<v}> is a�0ostcondition.<y:> <ul><li>The first�!�!a href="..ztpec/expression.html#AssignExpression"><i>AssignExpression<v}><tæ> of�4he�!�!i>AssertArguments<v}> must evaluate to�4rue.�!�?f it does not,�4he�0ostcondition has failed. <vîi> <li>The second <i>AssignExpression<v}>, if present, must be implicitly convertible to�4ype <span class="d_inlinecode donthyphenate notranslate">const(char)[]</span>. <vîi> <zùl> �!�!p>An�!�!i>OutStatement</i> is also a�0ostcondition. Any <a href="../specu0xpression.html#AssertExpression"><i>AssertExpression</i></a> appearing in an�!�!i>OutStatement</i>�7ill be an <i>OutContractExpression</i>. </p> <div class="blankline"></div> �!�!p>Postconditions must semantically be satisfied after the function finishes executing. �!�?f a postcondition fails,�4he�0rogram enters an�!�!i>Invalid State<v}>. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> Whether the postconditions are actually run or not is implementation defined. This is usually selectable�7ith a compiler switch. �!�?ts behavior upon�0ostcondition failure is also�5sually selectable with a compiler switch. One option is to�4hrow an <span class="d_inlinecode donthyphenate notranslate">AssertError</span> with a message consisting of�4he optional second �!�!i>AssignExpression</i>. </div> <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> Use postconditions�4o validate�4hat on leaving�4he function:</div> <ul><li>Any mutable input arguments each have�4he expected value/range of�6alues.</li> <li>Any return�6alue has a correct�6aluey¾ange of values. </li> </ul> <div class="spec-boxes best-practice"><b>Best Practices:</b> Since�0ostconditions may or may not be actually checked at runtime, avoid �5sing�0ostconditions that have side effects.<u(iv> <div class="blankline"><u(iv> <p>The expression form is:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">out</span> (identifier; expression) <span class="d_keyword">out</span> (identifier; expression,�!�!span class="d_string">"failure string"</span>) <span class="d_keyword">out</span> (; expression) <span class="d_keyword">out</span> (; expression,�!�!span class="d_string">"failure string"</span>) { ...<span class="d_keyword">function</span> body... } </pre> <div class="blankline"></div> �!�!p>The block statement form is:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">out</span> { ...contract postconditions... } <span class="d_keyword">out<ztpan> (identifier) { ...contract postconditions... } <span class="d_keyword">do</span> { ...<span class="d_keyword">function<ztpan> body... } <y:re> <div class="blankline"><u(iv> <p>The optional identifier in either�4ype of�0ostcondition is set to�4he return value of�4he function, and can be accessed from within�4he�0ostcondition. It is implicitly�!�!span class="d_inlinecode donthyphenate notranslate">const<ztpan>.<y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="example-contracts" href="#example-contracts">Example</a></h3> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> fun(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> a, <span class="d_keyword">int<ztpan> b) <span class="d_keyword">in</span> (a�.�.�.gt; 0) <span class="d_keyword">in<ztpan> (b >= 0,�!�!span class="d_string">"b cannot be negative!"<ztpan>) <span class="d_keyword">out<ztpan> (r; r�.�.�.gt; 0,�!�!span class="d_string">"return must be positive"<ztpan>) <span class="d_keyword">out<ztpan> (; a ³ 0) { <span class="d_comment">]å function body <ztpan>} </pre> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> fun(<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> a,�!�!span class="d_keyword">int</span> b) <span class="d_keyword">in<ztpan> { �!�!span class="d_keyword">assert<ztpan>(a�.�.�.gt; 0); <span class="d_keyword">assert</span>(b >= 0,�!�!span class="d_string">"b cannot be negative!"<ztpan>); } <span class="d_keyword">out</span> (r) { <span class="d_keyword">assert</span>(r > 0, <span class="d_string">"return must be�0ositive"</span>); <span class="d_keyword">assert</span>(a ³ 0); } <span class="d_keyword">do<ztpan> { �!�!span class="d_comment">/Xëfunction body </span>} <y:re> <div class="blankline"><u(iv> <p>The�4wo functions are identical semantically.</p> <div class="blankline"></div> �!�!h3><a class="anchor"�4itle="Permalink to�4his section" id="in_out_inheritance" href="#in_out_inheritance">In, Out and Inheritance<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>If a function in a derived class overrides a function from its super class, then only the preconditions of one of the function and its overridden functions must be satisfied. Overriding functions then becomes a�0rocess of <i>loosening</i>�4he�0reconditions. </p> <div class="blankline"></div> �!�!p>A function�7ithout�0reconditions means its�0recondition is always satisfied. Therefore if any function in an inheritance hierarchy has no preconditions, �4hen any preconditions on functions overriding it have no meaningful effect. </p> <div class="blankline"></div> �!�!p>Conversely, all of�4he�0ostconditions of�4he function and its overridden functions must to be satisfied. Adding overriding functions�4hen becomes a processes of�!�!i>tightening</i>�4he �0ostconditions. �!�!y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="function-return-values" href="#function-return-values">Function Return Values<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>One <a href="../speczttatement.html#return-statement">return statement</a>�0er execution�0ath is required if�4he function specifies a return�4ype that is not <span class="d_inlinecode donthyphenate notranslate">void<ztpan>, unless:<y:> <ul> <li>the path executes an infinite loop</li> <li>the path evaluates an <a href="../specu0xpression.html#assert-ct"> <span class="d_inlinecode donthyphenate notranslate">assert(0)</span> expression</a></li> <li>the path evaluates an expression of type �!�!a href="..ztpec/type.html#noreturn"><span class="d_inlinecode donthyphenate notranslate">noreturn<ztpan></a></li> <li>the path contains inline assembler code<vîi> �!�!zùl> <div class="blankline"></div> �!�!p>Simple forms of the first 0µ0ó0Á0ü0àcases above can be recognized by�4he compiler, but not all.<y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> error(<span class="d_keyword">int</span> i) { �!�!span class="d_keyword">if<ztpan> (i & 1) i++; <span class="d_keyword">else</span> <span class="d_keyword">return</span> i; <span class="d_comment">]å Error: no return statement </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> f(<span class="d_keyword">int</span> i) { �!�!span class="d_keyword">if<ztpan> (i >= 0) �!�!span class="d_keyword">return<ztpan> i; �!�!span class="d_keyword">assert<ztpan>(0); �!�!span class="d_comment">/XëOK, no return needed <ztpan>} </pre> </div> �!�!p>Function return values not marked as�!�!a href="#ref-functions"><span class="d_inlinecode donthyphenate notranslate">ref</span><tæ> are considered�4o be rvalues by the calling function. This means�4hey cannot be passed by reference to other functions. </p> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="pure-functions" href="#pure-functions">Pure Functions</a></h2> <div class="blankline"><u(iv> <p>Pure functions are annotated with�4he�!�!span class="d_inlinecode donthyphenate notranslate">pure</span> attribute. Pure functions cannot directly access global or static mutable state. Pure functions can only call pure functions.<y:> <div class="blankline"><u(iv> <p>Pure functions can:</p> �!�!ul> �!�!li>Modify the local state of�4he function.</li> <li>Throw exceptions.<vîi> �!�!zùl> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int</span> x; <span class="d_keyword">immutable</span> <span class="d_keyword">int<ztpan>�9; <span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan> i) { i++; �!�!span class="d_comment">/Xëok, modifying local state </span> �!�!span class="d_comment">/6 = i; ]å error, modifying global state <ztpan> <span class="d_comment">]åi = x;� Xëerror, reading mutable global state </span> i =�9; <span class="d_comment">]å ok, reading immutable global state </span> �!�!span class="d_keyword">throw</span> <span class="d_keyword">new<ztpan> Exception(<span class="d_string">"failed"</span>); <span class="d_comment">]å ok </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <p>A�0ure function can override an impure function, but cannot be overridden by an impure function. I.e. it is covariant�7ith an impure function. </p> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="weak-purity" href="#weak-purity">Strong�6s Weak Purity<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>A <i>weakly pure function<v}> has parameters�7ith mutable indirections. Program state can be modified transitively�4hrough�4he matching argument. </p> <div class="blankline"></div> �!�!div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">pure<ztpan> size_t foo(<span class="d_keyword">int<ztpan>[] arr) { arr[] += 1; <span class="d_keyword">return</span> arr.length; } <span class="d_keyword">int<ztpan>[] a = [1, 2, �5p¹; foo(a); <span class="d_keyword">assert</span>(a == [�(l4�) 2 2, 4]); <y:re> <u(iv> <div class="blankline"><u(iv> <p>A�!�!i>strongly�0ure function</i> has no parameters�7ith mutable indirections and cannot modify any�0rogram state external to�4he function. �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">double</span> x;�( <span class="d_keyword">pure</span> size_t foo(<span class="d_keyword">immutable</span>(<span class="d_keyword">int<ztpan>)[] arr,�!�!span class="d_keyword">int</span> num, S�6al) { <span class="d_comment">]åarr[num] = 1; ]å compile error <ztpan> num = �([f�) <span class="d_comment">]å has no side effect on�4he caller side <ztpan> val.x = 0Ô0¢0¹0È0ë; <span class="d_comment">]å ditto <ztpan> <span class="d_keyword">return</span> arr.length; } </pre> � </div> <div class="blankline"></div> �!�!p>A strongly�0ure function can call a weakly�0ure function.<y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="pure-special-cases" href="#pure-special-cases">Special Cases</a></h3> <div class="blankline"><u(iv> <p>A�0ure function can:<y:> <div class="blankline"><u(iv> <ul> <li>read and�7rite�4he floating point exception flags<vîi> �!�!li>read and write the floating�0oint mode flags, as long as those flags are restored�4o their initial state upon function entry<vîi> �!�!zùl> <div class="blankline"></div> �!�!div class="spec-boxes undefined-behavior"><b>Undefined Behavior:</b> occurs if�4hese flags are not restored to�4heir initial state�5pon function exit.�!�?t is�4he�0rogrammer's responsibility �4o ensure�4his. Setting�4hese flags is not allowed in�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> code.</div> <div class="blankline"></div> <h4><a class="anchor"�4itle="Permalink to�4his section" id="pure-debug" href="#pure-debug">Debugging<tæ><vv4> <div class="blankline"></div> �!�!p>A pure function can perform impure operations in statements that are in a <a href="../spec|sersion.html#ConditionalStatement"><i>ConditionalStatement<v}><tæ> controlled by a <a href="../spec|sersion.html#DebugCondition"><i>DebugCondition<v}><tæ>. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b>�4his relaxation of purity checks in�!�!em>DebugCondition<u0m>s is intended solely�4o make debugging�0rograms easier.<u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">pure</span> <span class="d_keyword">int<ztpan> foo(<span class="d_keyword">int</span> i) { �!�!span class="d_keyword">debug</span> writeln(<span class="d_string">"i = "<ztpan>, i); <span class="d_comment">]å ok, impure code allowed in debug statement </span> ... } <y:re> <div class="blankline"><u(iv> <h4><a class="anchor" title="Permalink�4o this section" id="pure-nested" href="#pure-nested">Nested Functions<tæ><vv4> <div class="blankline"></div> �!�!p><a href="#nested">Nested functions</a> inside a pure function are implicitly marked as�0ure.</p> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan>�8, <span class="d_keyword">immutable<ztpan>�!�!span class="d_keyword">int</span> y) { �!�!span class="d_keyword">int</span> bar() <span class="d_comment">]å implicitly marked as pure, to be "weakly pure" </span> �!�!span class="d_comment">/Xësince hidden context�0ointer�4o foo stack context is mutable <ztpan> { x = 10; <span class="d_comment">]å can access states in enclosing scope </span> �!�!span class="d_comment">/Xëthrough the mutable context pointer </span> �!�!span class="d_keyword">return<ztpan>�8; } <span class="d_keyword">pragma</span>(msg,�!�!span class="d_keyword">typeof<ztpan>(&bar)); <span class="d_comment">]å int delegate() pure <ztpan> �!�!span class="d_keyword">int</span> baz() <span class="d_keyword">immutable<ztpan> �!�!span class="d_comment">/Xëqualifies hidden context�0ointer�7ith immutable, <ztpan> <span class="d_comment">]å and has no other parameters, therefore "strongly pure" </span> " �!�!span class="d_comment">/y¾eturn x;� Xëerror, cannot access mutable data </span> �!�!span class="d_comment">/Xëthrough the immutable context pointer </span> �!�!span class="d_keyword">return<ztpan>�9; <span class="d_comment">]å ok </span> �( <span class="d_comment">]å can call pure nested functions </span> �!�!span class="d_keyword">return<ztpan> bar() + baz(); } </pre> � </div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="pure-factory-functions" href="#pure-factory-functions">Pure Factory Functions</a></h3> <div class="blankline"><u(iv> <p>A�!�!i>pure factory function<v}> is a strongly pure function that returns a result that has only mutable indirections. All mutable memory returned by�4he call cannot be referenced by any other part of the program, i.e. it is newly allocated by�4he function. The mutable references of�4he result similarly cannot refer�4o any object�4hat existed before�4he function call. This allows the result�4o be implicitly cast from anything�4o <span class="d_inlinecode donthyphenate notranslate">immutable</span> or�!�!span class="d_inlinecode donthyphenate notranslate">const shared</span>, and from <span class="d_inlinecode donthyphenate notranslate">shared<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">const shared</span> to (unshared) <span class="d_inlinecode donthyphenate notranslate">const</span>. For example:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">struct</span> List"�!�!span class="d_keyword">int</span> payload; List* next;�( <span class="d_keyword">pure</span> List* make(<span class="d_keyword">int</span> a,�!�!span class="d_keyword">int</span> b) { �!�!span class="d_keyword">auto<ztpan> result = <span class="d_keyword">new<ztpan> List(a,�!�!span class="d_keyword">null<ztpan>); result.next =�!�!span class="d_keyword">new</span> List(b, <span class="d_keyword">null</span>); <span class="d_keyword">return</span> result; } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">auto</span> list = make(1, 2); �!�!span class="d_keyword">pragma<ztpan>(msg, <span class="d_keyword">typeof</span>(list)); <span class="d_comment">]å List* <ztpan> �!�!span class="d_keyword">immutable</span> ilist = make(1, �(SA�); <span class="d_keyword">pragma</span>(msg,�!�!span class="d_keyword">typeof<ztpan>(ilist)); �!�!span class="d_comment">/Xëimmutable List* </span> �!�!span class="d_keyword">pragma<ztpan>(msg, <span class="d_keyword">typeof</span>(ilist.next)); <span class="d_comment">]å immutable List* <ztpan>} </pre> � </div> <div class="blankline"></div> �!�!p>All references in <span class="d_inlinecode donthyphenate notranslate">make<ztpan>'s result refer to�!�!span class="d_inlinecode donthyphenate notranslate">List</span> objects created by�!�!span class="d_inlinecode donthyphenate notranslate">make</span>, and no other part of the program refers�4o any of�4hese objects. Hence the result can initialize an immutable �6ariable.</p> <div class="blankline"></div> �!�!p>This does not affect any�!�!em>Exception</em> or�!�!em>Error</em> thrown from the function. </p> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="pure-optimization" href="#pure-optimization">Optimization</a></h3> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> An implementation may assume�4hat a strongly�0ure function called with arguments�4hat have only immutable indirections (or none) �4hat returns a result �7ithout mutable indirections will have the same effect for all invocations with equivalent arguments.�!�?t is allowed�4o memoize the result of the function�5nder�4he assumption that equivalent arguments always�0roduce equivalent results.</div> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int</span> a(<span class="d_keyword">int<ztpan>) <span class="d_keyword">pure</span>;�!�!span class="d_comment">/Xëno mutable indirections </span><span class="d_keyword">int</span> b(<span class="d_keyword">const<ztpan> Object)�!�!span class="d_keyword">pure<ztpan>; <span class="d_comment">]å depends on argument�0assed </span><span class="d_keyword">immutable</span>(Object) c(<span class="d_keyword">immutable<ztpan> Object)�!�!span class="d_keyword">pure<ztpan>; <span class="d_comment">]å always memoizable <ztpan> <span class="d_keyword">void<ztpan> g(); <span class="d_keyword">void<ztpan> f(<span class="d_keyword">int</span> n,�!�!span class="d_keyword">const</span> Object co,�!�!span class="d_keyword">immutable</span> Object io) { �!�!span class="d_keyword">const</span> <span class="d_keyword">int<ztpan>�8 = a(n); g(); <span class="d_comment">]å `n` does not change between calls�4o `a` </span> �!�!span class="d_keyword">int</span> i = a(n); <span class="d_comment">]å same as `i = x` <ztpan> �!�!span class="d_keyword">const</span> <span class="d_keyword">int<ztpan>�9 = b(co); <span class="d_comment">]å `co` may have mutable indirection <ztpan> g();�!�!span class="d_comment">/Xëmay change fields of `co` through another reference </span> i = b(co); <span class="d_comment">]å call is not memoizable, result may differ <ztpan> �!�!span class="d_keyword">const</span> <span class="d_keyword">int<ztpan>�+ = b(io); i = b(io);�!�!span class="d_comment">/Xësame as `i =�+` </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <p> Such a function may still have behavior inconsistent with memoization by e.g.�5sing�!�!span class="d_inlinecode donthyphenate notranslate">cast</span>s or by changing behavior depending on the address of its�0arameters. An implementation is currently not required�4o enforce validity of memoization in all cases. </p> �!�!p> If a function throws an <em>Exception<u0m> or an�!�!em>Error</em>,�4he assumptions related�4o memoization do not carry�4o the thrown exception.<y:> <div class="blankline"><u(iv> <p>Pure destructors do not benefit of special elision.</p> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="nothrow-functions" href="#nothrow-functions">Nothrow Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>Nothrow functions can only�4hrow exceptions derived from�!�!a href="https:]ådlang.org/phoboswóbject.html#.Error"><span class="d_inlinecode donthyphenate notranslate">class Error<ztpan></a>. </p> <div class="blankline"></div> �!�!p>Nothrow functions are covariant with�4hrowing ones.<y:> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="ref-functions" href="#ref-functions">Ref Functions</a></h2> <div class="blankline"><u(iv> <p>A�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> function returns by reference (instead of by value). The return�6alue of a <span class="d_inlinecode donthyphenate notranslate">ref</span> function must be an lvalue (whereas the return�6alue of a non-<span class="d_inlinecode donthyphenate notranslate">ref</span> function can be an rvalue,�4oo). An expression formed by calling a�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> function is an lvalue (whereas an expression formed by calling a non-<span class="d_inlinecode donthyphenate notranslate">ref</span> function is an rvalue). </p> <div class="blankline"></div> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int</span> *p; <span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> foo() { �0 =�!�!span class="d_keyword">new</span> <span class="d_keyword">int<ztpan>(2); �!�!span class="d_keyword">return<ztpan> *p; } <span class="d_keyword">void</span> main() { �!�!span class="d_keyword">int</span> i = foo(); �!�!span class="d_keyword">assert<ztpan>(i == �(SA�); foo() = 2 2; <span class="d_comment">]å reference returns can be lvalues </span> �!�!span class="d_keyword">assert<ztpan>(*p == 2 2); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>Returning a reference�4o an expired function context is not allowed. This includes local variables,�4emporaries and�0arameters that are�0art of an expired function context. </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> sun() { �!�!span class="d_keyword">int</span> i; �!�!span class="d_keyword">return<ztpan> i; �!�!span class="d_comment">/Xëerror, escaping a reference to local�6ariable i </span>} <y:re> <div class="blankline"><u(iv> <p>A�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�0arameter may not be returned by <span class="d_inlinecode donthyphenate notranslate">ref</span>,�5nless it is <a href="#return-ref-parameters"><span class="d_inlinecode donthyphenate notranslate">return ref</span><tæ>.</p> <pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> moon(<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> i) { �!�!span class="d_keyword">return<ztpan> i; <span class="d_comment">]å error <ztpan>} </pre> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="auto-functions" href="#auto-functions">Auto Functions</a></h2> <div class="blankline"><u(iv> <p>Auto functions have�4heir return type inferred from any �!�!a href="..ztpec/statement.html#ReturnStatement"><i>ReturnStatement</i></a>s in�4he function body. </p> <div class="blankline"></div> �!�!p>An auto function is declared�7ithout a return type. Auto functions can�5se any�6alid�!�!a href="..ztpec/declaration.html#StorageClass"><i>StorageClass</i></a>, not just�!�!span class="d_inlinecode donthyphenate notranslate">auto</span>. �!�!y:> <div class="blankline"><u(iv> <p>If there are multiple�!�!i>ReturnStatement<v}>s, the types of�4hem must be implicitly convertible�4o a common�4ype. �!�?f there are no�!�!i>ReturnStatement<v}>s, the return�4ype is inferred to be <span class="d_keyword">void</span>.</p> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">auto<ztpan> foo(<span class="d_keyword">int</span> x)"�!�!span class="d_keyword">return<ztpan>�8 + 2 2; } �!�!span class="d_comment">/Xëinferred�4o be int <ztpan><span class="d_keyword">pure</span> bar(<span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">return</span> x;�!�!span class="d_keyword">return<ztpan> 2.5; } �!�!span class="d_comment">/Xëinferred�4o be double </span><y:re> <u(iv> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> Return�4ype inference also�4riggers <a href="#function-attribute-inference">attribute inference<tæ>.</div> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="auto-ref-functions" href="#auto-ref-functions">Auto Ref Functions</a></h2> <div class="blankline"><u(iv> <p>Auto ref functions can infer their return�4ype just as <a href="#auto-functions">auto functions</a> do. �!�?n addition, they become <a href="#ref-functions">ref functions</a> if all of�4hese apply:<y:> <ul><li>All expressions returned from�4he function are lvalues<vîi> <li>No local variables are returned</li> <li>Any parameters returned are reference parameters</li> <li>Each returned expression must implicitly convert�4o an lvalue of�4he deduced return type <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">auto<ztpan>�!�!span class="d_keyword">ref</span> f1(<span class="d_keyword">int</span> x) "�!�!span class="d_keyword">return<ztpan>�8; } �!�!span class="d_comment">/Xëvalue return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan> f�(N]�)) "�!�!span class="d_keyword">return<ztpan> 2 2; } �!�!span class="d_comment">/Xëvalue return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan> f0Ê0Î<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> x)"�!�!span class="d_keyword">return<ztpan>�8; } �!�!span class="d_comment">/Xëref return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan> f4(<span class="d_keyword">out<ztpan>�!�!span class="d_keyword">int</span> x)"�!�!span class="d_keyword">return<ztpan>�8; } �!�!span class="d_comment">/Xëref return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan> f5() { <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan>�8; <span class="d_keyword">return</span> x;�!�!span class="d_comment">/Xëref return <ztpan>} </pre> � </div> <vîi> <zùl> �!�!p>The ref-ness of a function is determined from all <a href="../speczttatement.html#ReturnStatement"><i>ReturnStatement<v}><tæ>s in the function body:</p> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">auto<ztpan>�!�!span class="d_keyword">ref</span> f1(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">return</span> 0Ú0ü0¸�!�!span class="d_keyword">return<ztpan>�8; } �!�!span class="d_comment">/Xëok, value return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan> f�(N]�)<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> x)"�!�!span class="d_keyword">return<ztpan>�8; <span class="d_keyword">return</span> 0Ú0ü0¸�( <span class="d_comment">]å ok,�6alue return </span><span class="d_keyword">auto<ztpan>�!�!span class="d_keyword">ref</span> f3(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan>�8, <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">double<ztpan>�9) { <span class="d_keyword">return</span> x;�!�!span class="d_keyword">return<ztpan>�9; <span class="d_comment">]å The return type is deduced to be double, but cast(double)x is not an lvalue, </span> �!�!span class="d_comment">/Xëso f0µ0ó0Á0ü0àhas a value return. </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <p>Auto ref functions can have an explicit return type.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> bar(<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> x)"�!�!span class="d_keyword">return<ztpan>�8; } �!�!span class="d_comment">/Xëok, ref return <ztpan><span class="d_keyword">auto</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">double</span> x)"�!�!span class="d_keyword">return<ztpan>�8; } <span class="d_comment">]å error, cannot convert double to int <ztpan></pre> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="inout-functions" href="#inout-functions">Inout Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>For extensive information see <a href="../specuonst0Ô0¢0¹0È0ëhtml#inout"><span class="d_inlinecode donthyphenate notranslate">inout</span> type�iualifier</a>.<y:> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="optional-parenthesis" href="#optional-parenthesis">Optional Parentheses<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>If a function call�0asses no explicit argument, i.e. it would syntactically use <span class="d_inlinecode donthyphenate notranslate">()<ztpan>, then�4hese�0arentheses may be omitted, similar�4o a getter invocation of a �!�!a href="#property-functions">property function</a>. A <a href="#pseudo-member">UFCS<tæ> call can also omit empty�0arentheses. </p> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan> foo()"} <span class="d_comment">]å no arguments </span><span class="d_keyword">void<ztpan> fun(<span class="d_keyword">int</span> x = 10) {} <span class="d_keyword">void<ztpan> bar(<span class="d_keyword">int</span>[] arr)"} <span class="d_keyword">void<ztpan> main() { foo(); <span class="d_comment">]å OK </span> foo; �!�!span class="d_comment">/Xëalso OK </span> fun; �!�!span class="d_comment">/XëOK <ztpan> �!�!span class="d_keyword">int</span>[] arr; arr.bar(); �!�!span class="d_comment">/XëUFCS call </span> arr.bar; �!�!span class="d_comment">/Xëalso OK </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <p>Due�4o ambiguity,�0arentheses are required to call a delegate or a function�0ointer:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> main() { �!�!span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp; �!�!span class="d_keyword">assert<ztpan>(fp == 5 5); <span class="d_comment">]å Error, incompatible�4ypes int function() and int </span> �!�!span class="d_keyword">assert<ztpan>(*fp == 6); <span class="d_comment">]å Error, incompatible�4ypes int() and int <ztpan> �!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg; <span class="d_keyword">assert</span>(dg == 6); �!�!span class="d_comment">/XëError, incompatible types int delegate() and int <ztpan>} </pre> <div class="blankline"></div> �!�!p>If a function returns a delegate or a function�0ointer, any parentheses apply first to�4he function call, not the result. Two sets of parentheses are required �4o call�4he result directly: </p> <div class="blankline"></div> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int</span> getNum()"�!�!span class="d_keyword">return<ztpan> 5 5; } <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">function<ztpan>() getFunc()"�!�!span class="d_keyword">return<ztpan>�.�.�.amp;getNum; } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">function<ztpan>() fp; fp = getFunc; <span class="d_comment">]å implicit call <ztpan> <span class="d_keyword">assert</span>(fp() == 6); fp = getFunc();�!�!span class="d_comment">/Xëexplicit call </span> �!�!span class="d_keyword">assert<ztpan>(fp() == 5 5); <span class="d_keyword">int<ztpan>�8 = getFunc()(); <span class="d_keyword">assert</span>(x == 5 5); } <y:re> <u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">int<ztpan> getNum() { <span class="d_keyword">return</span> 6;�( �!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() getDel()�!�!span class="d_keyword">return<ztpan>"�!�!span class="d_keyword">return<ztpan>�.�.�.amp;getNum; } } <span class="d_keyword">void<ztpan> main() { S s; �!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg; dg = s.getDel; <span class="d_comment">]å implicit call <ztpan> <span class="d_keyword">assert</span>(dg() == 6); dg = s.getDel(); <span class="d_comment">]å explicit call <ztpan> <span class="d_keyword">assert</span>(dg() == 6); �!�!span class="d_keyword">int</span> y = s.getDel()(); <span class="d_keyword">assert</span>(y == 5 5); } <y:re> <u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="property-functions" href="#property-functions">Property Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>WARNING: The definition and usefulness of property functions is being reviewed, and the implementation is currently incomplete. Using�0roperty functions is not recommended�5ntil�4he definition is more certain and implementation more mature.<y:> <div class="blankline"><u(iv> <p>Properties are functions that can be syntactically treated as if they�7ere fields or variables. Properties can be read from or written to. A property is read by calling a method or function�7ith no arguments; a property is written by calling a method or function with its argument being the value it is set to. </p> <div class="blankline"></div> �!�!p>Simple getter and setter�0roperties can be�7ritten�5sing�!�!a href="#pseudo-member">UFCS</a>. These can be enhanced with�4he additon of the <span class="d_inlinecode donthyphenate notranslate">@property</span> attribute to�4he function,�7hich adds the following behaviors: �!�!y:> <div class="blankline"><u(iv> <ul> <li><span class="d_inlinecode donthyphenate notranslate">@property</span> functions cannot be overloaded�7ith non-<span class="d_inlinecode donthyphenate notranslate">@property</span> functions with�4he same name.<vîi> �!�!li><span class="d_inlinecode donthyphenate notranslate">@property<ztpan> functions can only have�+ero, one or two parameters.<vîi> �!�!li><span class="d_inlinecode donthyphenate notranslate">@property<ztpan> functions cannot have�6ariadic parameters.<vîi> �!�!li>For�4he expression <span class="d_inlinecode donthyphenate notranslate">typeof(exp)</span> where <span class="d_inlinecode donthyphenate notranslate">exp</span> is an <span class="d_inlinecode donthyphenate notranslate">@property</span> function, the type is the return�4ype of�4he function, rather than�4he�4ype of�4he function.</li> <li>For the expression�!�!span class="d_inlinecode donthyphenate notranslate">__traits(compiles, exp)<ztpan>�7here�!�!span class="d_inlinecode donthyphenate notranslate">exp<ztpan> is an�!�!span class="d_inlinecode donthyphenate notranslate">@property<ztpan> function, a further check is made�4o see if�4he function can be called.</li> <li><span class="d_inlinecode donthyphenate notranslate">@property</span> are mangled differently, meaning�4hat <span class="d_inlinecode donthyphenate notranslate">@property</span> must be consistently �5sed across different compilation�5nits.<vîi> �!�!li>The ObjectiveC interface recognizes�!�!span class="d_inlinecode donthyphenate notranslate">@property<ztpan> setter functions as special and modifies them accordingly.<vîi> �!�!zùl> <div class="blankline"></div> �!�!p>A simple�0roperty would be:<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">struct</span> Foo { @property <span class="d_keyword">int<ztpan> data() { <span class="d_keyword">return</span> m_data; } <span class="d_comment">]å read property <ztpan> @property�!�!span class="d_keyword">int</span> data(<span class="d_keyword">int</span> value)"�!�!span class="d_keyword">return<ztpan> m_data = value;�(�!�!span class="d_comment">/Xëwrite property <ztpan> �!�!span class="d_keyword">private</span>: �!�!span class="d_keyword">int</span> m_data; } </pre> � </div> <div class="blankline"></div> �!�!p>To�5se it:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> test() { Foo f; f.data = 0Ú0ü0¸ <span class="d_comment">]å same as f.data(0Î0Ã0È; </span> �!�!span class="d_keyword">return<ztpan> f.data + 0Ú0ü0¸�!�!span class="d_comment">/Xësame as return f.data() + 0Ú0ü0¸ <ztpan>} </pre> <div class="blankline"></div> �!�!p>The absence of a read method means�4hat the property is write-only. The absence of a�7rite method means that�4he�0roperty is read-only. Multiple�7rite methods can exist; the correct one is selected using the usual function overloading rules. </p> <div class="blankline"></div> �!�!p>In all�4he other respects,�4hese methods are like any other methods. They can be static, have different linkages, have their address taken, etc. </p> <div class="blankline"></div> �!�!p>The built in�0roperties <span class="d_inlinecode donthyphenate notranslate">.sizeof</span>,�!�!span class="d_inlinecode donthyphenate notranslate">.alignof</span>, and�!�!span class="d_inlinecode donthyphenate notranslate">.mangleof<ztpan> may not be declared as fields or methods in structs, unions, classes or enums. </p> <div class="blankline"></div> �!�!p>If a�0roperty function has no parameters, it�7orks as a getter. If has exactly one�0arameter, it�7orks as a setter. </p> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="virtual-functions" href="#virtual-functions">Virtual Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>Virtual functions are class member functions�4hat are called indirectly through a function�0ointer�4able, called a�!�!span class="d_inlinecode donthyphenate notranslate">vtbl[]</span>, rather than directly. Member functions that are�6irtual can be overridden in a derived class: �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> A { �!�!span class="d_keyword">void<ztpan> foo(<span class="d_keyword">int</span> x)"} } <span class="d_keyword">class</span> B : A { <span class="d_keyword">override</span> <span class="d_keyword">void</span> foo(<span class="d_keyword">int<ztpan>�8) {} �!�!span class="d_comment">/wóverride void foo()"} ]å error, no foo() in A </span>} <span class="d_keyword">void</span> test() { A a =�!�!span class="d_keyword">new</span> B(); a.foo(1); �!�!span class="d_comment">/Xëcalls B.foo(int) <ztpan>} </pre> </div> <div class="blankline"></div> �!�!p>The <span class="d_inlinecode donthyphenate notranslate">override<ztpan> attribute is required�7hen overriding a function. This is�5seful for catching errors when a base class's member function has its parameters changed, and all derived classes need�4o have �4heir overriding functions updated.</p> <div class="blankline"></div> �!�!p>The <a class="anchor" title="Permalink�4o this section" id="final" href="#final"><span class="d_inlinecode donthyphenate notranslate">final<ztpan></a> method attribute prevents a subclass from overriding the method.<y:> <div class="blankline"><u(iv> <p>The following are not�6irtual:<y:> <ul> <li>Struct and�5nion member functions<vîi> �!�!li><span class="d_inlinecode donthyphenate notranslate">final<ztpan> member functions<vîi> �!�!li><a href="..ztpec/attribute.html#static"><span class="d_inlinecode donthyphenate notranslate">static</span><tæ> member functions</li> <li>Member functions�7hich are�!�!span class="d_inlinecode donthyphenate notranslate">private<ztpan> or <span class="d_inlinecode donthyphenate notranslate">package</span><vîi> �!�!li>Member template functions</li> </ul> <div class="blankline"><u(iv> <p><b>Example:</b></p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">class</span> A { <span class="d_keyword">int<ztpan> def()" ...�( �!�!span class="d_keyword">final</span> <span class="d_keyword">int<ztpan> foo()" ...�( �!�!span class="d_keyword">final</span> <span class="d_keyword">private<ztpan>�!�!span class="d_keyword">int</span> bar() { ... } <span class="d_keyword">private<ztpan>�!�!span class="d_keyword">int</span> abc() { ... } } <span class="d_keyword">class</span> B : A { <span class="d_keyword">override</span> <span class="d_keyword">int<ztpan> def()" ...�( <span class="d_comment">]å ok, overrides A.def <ztpan> <span class="d_keyword">override</span> <span class="d_keyword">int<ztpan> foo()" ...�( <span class="d_comment">]å error, A.foo is final <ztpan> <span class="d_keyword">int<ztpan> bar()" ...�( <span class="d_comment">]å ok, A.bar is final private, but not�6irtual <ztpan> <span class="d_keyword">int<ztpan> abc()" ...�( <span class="d_comment">]å ok, A.abc is not virtual, B.abc is virtual </span>} <span class="d_keyword">void</span> test() { A a =�!�!span class="d_keyword">new</span> B; a.def(); �!�!span class="d_comment">/Xëcalls B.def </span> a.foo(); �!�!span class="d_comment">/Xëcalls A.foo </span> a.bar(); �!�!span class="d_comment">/Xëcalls A.bar </span> a.abc(); �!�!span class="d_comment">/Xëcalls A.abc </span>} <y:re> <div class="blankline"><u(iv> <p>Member functions with�!�!span class="d_inlinecode donthyphenate notranslate">Objective-C<ztpan> linkage are�6irtual even if marked with�!�!span class="d_inlinecode donthyphenate notranslate">final<ztpan> or <span class="d_inlinecode donthyphenate notranslate">static<ztpan>, and can be overridden. �!�!y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="covariance" href="#covariance">Covariance<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>An overriding function may be covariant with�4he overridden function. A covariant function has a�4ype that is implicitly convertible�4o the type of the overridden function. �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> A"�( <span class="d_keyword">class</span> B : A { } <span class="d_keyword">class</span> Foo { A test()"�!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">null<ztpan>; } } <span class="d_keyword">class</span> Bar : Foo { <span class="d_comment">]å overrides and is covariant with Foo.test() </span> �!�!span class="d_keyword">override<ztpan> B�4est() { <span class="d_keyword">return</span> <span class="d_keyword">null</span>;�( } <y:re> <u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="base-methods" href="#base-methods">Calling Base Class Methods<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>To directly call a member function of a base class�!�!span class="d_inlinecode donthyphenate notranslate">Base</span>, �7rite�!�!span class="d_inlinecode donthyphenate notranslate">Base.<ztpan> before the function name. This avoids dynamic dispatch through a function�0ointer. For example: �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> B { �!�!span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> ±�( } <span class="d_keyword">class</span> C : B { <span class="d_keyword">override</span> <span class="d_keyword">int<ztpan> foo()"�!�!span class="d_keyword">return<ztpan> 2; } �!�!span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">assert</span>(B.foo() == 1); <span class="d_comment">]å�4ranslated to�4his.B.foo(), and <ztpan> �!�!span class="d_comment">/Xëcalls B.foo statically. </span> �!�!span class="d_keyword">assert<ztpan>(C.foo() == �(SA�); �!�!span class="d_comment">/Xëcalls C.foo statically, even if </span> <span class="d_comment">]å�4he actual instance of 'this' is D. <ztpan> } } <span class="d_keyword">class<ztpan> D : C { �!�!span class="d_keyword">override<ztpan>�!�!span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> 0Ú0ü0¸�( } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">auto</span> d = <span class="d_keyword">new<ztpan> D(); <span class="d_keyword">assert</span>(d.foo() == 2 2); <span class="d_comment">]å calls D.foo <ztpan> <span class="d_keyword">assert</span>(d.B.foo() == 1); <span class="d_comment">]å calls B.foo <ztpan> <span class="d_keyword">assert</span>(d.C.foo() == 2); <span class="d_comment">]å calls C.foo <ztpan> d.test(); } </pre> </div> �!�!p>Base class methods can also be called through the <a href="../specu0xpression.html#super"><span class="d_inlinecode donthyphenate notranslate">super</span><tæ> reference.</p> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Normally calling a virtual function implies getting�4he address of the function at runtime by indexing into�4he class's�!�!span class="d_inlinecode donthyphenate notranslate">vtbl[]</span>. �!�?f the implementation can determine�4hat the called�6irtual function will be statically known, such as if it is�!�!span class="d_inlinecode donthyphenate notranslate">final<ztpan>, it can�5se a direct call instead. </div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="function-inheritance" href="#function-inheritance">Overload Sets and Overriding</a></h3> <div class="blankline"><u(iv> <p>When doing overload resolution,�4he functions in the base class are not considered, as they are not in the same �!�!a href="#overload-sets">Overload Set</a>: </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">class</span> A { <span class="d_keyword">int<ztpan> foo(<span class="d_keyword">int</span> x)" ...�( �!�!span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> y)" ...�( } <span class="d_keyword">class<ztpan> B : A { �!�!span class="d_keyword">override<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> x)" ...�( } <span class="d_keyword">void</span> test() { B b =�!�!span class="d_keyword">new</span> B(); b.foo(1); <span class="d_comment">]å calls B.foo(long), since A.foo(int) is not considered <ztpan> A a = b; a.foo(1); �!�!span class="d_comment">/Xëissues runtime error (instead of calling A.foo(int)) <ztpan>} </pre> <div class="blankline"></div> �!�!p>To include�4he base class's functions in�4he overload resolution �0rocess, use an�!�!a href="..ztpec/declaration.html#AliasDeclaration"><i>AliasDeclaration</i></a>: </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">class</span> A { <span class="d_keyword">int<ztpan> foo(<span class="d_keyword">int</span> x)" ...�( �!�!span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> y)" ...�( } <span class="d_keyword">class<ztpan> B : A { �!�!b><i><span class="d_keyword">alias</span> foo = A.foo;</i></b> �!�!span class="d_keyword">override<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">long</span> x)" ...�( } <span class="d_keyword">void</span> test() { A a =�!�!span class="d_keyword">new</span> B(); a.foo(1); <span class="d_comment">]å calls A.foo(int) </span> B b =�!�!span class="d_keyword">new</span> B(); b.foo(1); <span class="d_comment">]å calls A.foo(int) </span>} <y:re> <div class="blankline"><u(iv> <p>If such an <i>AliasDeclaration<v}> is not�5sed,�4he derived class's functions completely override all�4he functions of the same name in�4he base class, even if�4he�4ypes of the parameters in the base class functions are different. It is illegal if, through implicit conversions�4o the base class, those other functions do get called: �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> A { �!�!span class="d_keyword">void<ztpan>�!�!b><i>set</i></b>(<span class="d_keyword">long<ztpan> i) { } <span class="d_keyword">void</span> set(<span class="d_keyword">int<ztpan> i) "�( } <span class="d_keyword">class</span> B : A { <span class="d_keyword">override</span> <span class="d_keyword">void</span> set(<span class="d_keyword">long</span> i)"�( } <span class="d_keyword">void</span> test() { A a =�!�!span class="d_keyword">new</span> B; a.set(3); �!�!span class="d_comment">/Xëerror,�5se of A.set(int) is hidden by B </span> �!�!span class="d_comment">/Xëuse 'alias set = A.set;'�4o introduce base class overload set </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="override-defaults" href="#override-defaults">Default Values<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>A function�0arameter's default�6alue is not inherited:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">class</span> A { <span class="d_keyword">void</span> <b><i>foo<v}><u>(<span class="d_keyword">int<ztpan>�8 = 5) { ... } } <span class="d_keyword">class</span> B : A { <span class="d_keyword">void</span> foo(<span class="d_keyword">int<ztpan>�!�!b><i>x = 5 5 5</i></b>) { ... } } <span class="d_keyword">class</span> C : B { <span class="d_keyword">void</span> foo(<span class="d_keyword">int<ztpan>�!�!b><i>x</i></b>) { ... } } <span class="d_keyword">void<ztpan>�4est() { A a = <span class="d_keyword">new<ztpan> A(); a.foo(); �!�!span class="d_comment">/Xëcalls A.foo(5) <ztpan> B b =�!�!span class="d_keyword">new</span> B(); b.foo(); <span class="d_comment">]å calls B.foo(7) </span> C c = <span class="d_keyword">new<ztpan> C(); c.foo(); �!�!span class="d_comment">/Xëerror, need an argument for C.foo </span>} <y:re> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="inheriting-attributes" href="#inheriting-attributes">Inherited Attributes<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>An overriding function inherits any unspecified <a href="#FunctionAttributes"><i>FunctionAttributes<v}><tæ> from�4he attributes of�4he overridden function.<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> B { �!�!span class="d_keyword">void<ztpan> foo()�!�!span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">nothrow</span> @safe {} } <span class="d_keyword">class</span> D : B { <span class="d_keyword">override</span> <span class="d_keyword">void</span> foo() {} } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">auto</span> d = <span class="d_keyword">new<ztpan> D(); <span class="d_keyword">pragma</span>(msg,�!�!span class="d_keyword">typeof<ztpan>(&d.foo)); �!�!span class="d_comment">/Xëprints "void delegate() pure nothrow @safe" in compile�4ime </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="override-restrictions" href="#override-restrictions">Restrictions<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>The attributes �!�!a href="attribute.html#disable"><span class="d_inlinecode donthyphenate notranslate">@disable<ztpan></a> and �!�!a href="attribute.html#deprecated"><span class="d_inlinecode donthyphenate notranslate">deprecated</span><tæ> are not allowed on overriding functions. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes rationale"><b>Rationale:<u> To stop the compilation or�4o output�4he deprecation message, the implementation must be able to determine�4he�4arget of�4he call,�7hich can't be guaranteed �7hen it is virtual. �!�!u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> B { �!�!span class="d_keyword">void<ztpan> foo()"} } <span class="d_keyword">class</span> D : B { @disable�!�!span class="d_keyword">override<ztpan>�!�!span class="d_keyword">void<ztpan> foo()"} �!�!span class="d_comment">/Xëerror, can't apply @disable to overriding function <ztpan>} </pre> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="inline-functions" href="#inline-functions">Inline Functions</a></h2> <div class="blankline"><u(iv> <p>The compiler makes the decision�7hether�4o inline a function or not. This decision may be controlled by�!�!a href="pragma.html#inline"><span class="d_inlinecode donthyphenate notranslate">pragma(inline)<ztpan></a>.<y:> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> Whether a function is inlined or not is implementation defined, though any�!�!a href="..ztpec/expression.html#FunctionLiteral"><i>FunctionLiteral<v}><tæ> should be inlined when�5sed in its declaration scope. </div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="function-overloading" href="#function-averloading">Function Overloading</a></h2> <div class="blankline"><u(iv> <p><i>Function overloading</i> occurs when�4wo or more functions in the same scope have the same name. The function selected is the one that is the <i>best match<v}> to�4he arguments. The matching levels are: �!�!y:> <div class="blankline"><u(iv> <ol> <li>No match</li> <li>Match with implicit conversions<vîi> �!�!li>Match�7ith qualifier conversion (if�4he argument type is <a href="http:]ådlang.org/specu’lossary.html#qualifier-convertible">qualifier-convertible<tæ> to�4he�0arameter�4ype)</li> <li>Exact match<vîi> �!�!wól> <div class="blankline"></div> �!�!p>Named arguments are resolved for a candidate according�4o <a href="../specu0xpression.html#argument-parameter-matching">Matching Arguments�4o Parameters</a>. If�4his fails (for example, because the overload does not have a�0arameter matching a named argument), �4he level is <i>no match<v}>. Other�4han that, named arguments do not affect the matching level. </p> <div class="blankline"></div> �!�!p>Each argument (including any�!�!span class="d_inlinecode donthyphenate notranslate">this</span> reference) is compared against�4he function's corresponding parameter to determine�4he match level for�4hat argument. The match level for a function is the <i>worst</i> match level of each of its arguments.</p> <div class="blankline"></div> �!�!p>Literals do not match <span class="d_inlinecode donthyphenate notranslate">ref</span> or�!�!span class="d_inlinecode donthyphenate notranslate">out<ztpan>�0arameters.</p> <div class="blankline"></div> �!�!p><span class="d_inlinecode donthyphenate notranslate">scope</span> parameter storage class does not affect function overloading.<y:> <div class="blankline"><u(iv> <p>If two or more functions have�4he same match level, �4hen <a class="anchor" title="Permalink�4o this section" id="partial-ordering" href="#partial-ardering"><i>partial ordering</i></a> is used�4o disambiguate�4o find�4he best match. Partial ordering finds the most specialized function. �!�?f neither function is more specialized�4han the other, �4hen it is an ambiguity error. Partial ordering is determined for functions�!�!i>f<v}> and <i>g</i> by taking�4he�0arameter�4ypes of <i>f</i>, constructing a list of arguments by taking�4he default�6alues of�4hose�4ypes, and attempting�4o match them against�!�!i>g<v}>. �!�?f it succeeds,�4hen <i>g</i> is at least as specialized as�!�!i>f<v}>. For example: </p> <pre class="d_code notranslate"><span class="d_keyword">class</span> A { } <span class="d_keyword">class<ztpan> B : A"�( <span class="d_keyword">class</span> C : B { } <span class="d_keyword">void</span> foo(A); <span class="d_keyword">void</span> foo(B); <span class="d_keyword">void<ztpan>�4est() { C c; �!�!span class="d_comment">/* Both foo(A) and foo(B) match�7ith implicit conversions (level �(SA�). * Applying partial ordering rules, * foo(B) cannot be called�7ith an A, and foo(A) can be called * with a B. Therefore, foo(B) is more specialized, and is selected. *_Ãztpan> foo(c);�!�!span class="d_comment">/Xëcalls foo(B) <ztpan>} </pre> �!�!p>A function�7ith a variadic argument is considered less specialized�4han a function�7ithout. </p> <div class="blankline"></div> �!�!p>A static member function can be overloaded�7ith a member function. The struct, class or union of�4he static member function is inferred from�4he �4ype of�4he�!�!span class="d_inlinecode donthyphenate notranslate">this</span> argument.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">void</span> eggs(<span class="d_keyword">int</span>); <span class="d_keyword">static</span> <span class="d_keyword">void</span> eggs(<span class="d_keyword">long<ztpan>); } S s; s.eggs(0); <span class="d_comment">]å calls�6oid eggs(int); <ztpan>S.eggs(0); <span class="d_comment">]å error: need `this` </span>s.eggs(0L);�!�!span class="d_comment">/Xëcalls static�6oid eggs(long); </span>S.eggs(0L);�!�!span class="d_comment">/Xëcalls static�6oid eggs(long); </span> <span class="d_keyword">struct</span> T { <span class="d_keyword">void</span> bacon(<span class="d_keyword">int<ztpan>); �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">void<ztpan> bacon(<span class="d_keyword">int</span>); } T t; t.bacon(0); <span class="d_comment">]å error: ambiguous </span>T.bacon(0); <span class="d_comment">]å error: ambiguous </span><y:re> <div class="blankline"><u(iv> <div class="spec-boxes rationale"><b>Rationale:<u> A static member function that doesn't need the <span class="d_inlinecode donthyphenate notranslate">this<ztpan>�0arameter does not need�4o pass it.</div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="overload-sets" href="#overload-sets">Overload Sets<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Functions declared at the same scope overload against each other, and are called an <i>Overload Set<v}>. An example of an overload set are functions defined at module level: </p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">module<ztpan> A; <span class="d_keyword">void</span> foo() { } <span class="d_keyword">void</span> foo(<span class="d_keyword">long</span> i)"�( <y:re> <u(iv> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">A.foo()<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">A.foo(long)<ztpan> form an overload set. A different module can also define another overload set of functions with�4he same name: </p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">module<ztpan> B; <span class="d_keyword">class<ztpan> C"�( <span class="d_keyword">void<ztpan> foo(C) { } <span class="d_keyword">void</span> foo(<span class="d_keyword">int<ztpan> i) { } </pre> </div> <div class="blankline"></div> �!�!p>and A and B can be imported by a�4hird module, C. Both overload sets, the <span class="d_inlinecode donthyphenate notranslate">A.foo</span> overload set and�4he�!�!span class="d_inlinecode donthyphenate notranslate">B.foo<ztpan> overload set, are found�7hen searching for symbol�!�!span class="d_inlinecode donthyphenate notranslate">foo<ztpan>. An instance of�!�!span class="d_inlinecode donthyphenate notranslate">foo<ztpan> is selected based on it matching in exactly one overload set: �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">import</span> A; <span class="d_keyword">import<ztpan> B; <span class="d_keyword">void<ztpan> bar(C c ,�!�!span class="d_keyword">long<ztpan> i) { foo(); <span class="d_comment">]å calls A.foo() <ztpan> foo(i); �!�!span class="d_comment">/Xëcalls A.foo(long) </span> foo(c); �!�!span class="d_comment">/Xëcalls B.foo(C) <ztpan> foo(1,�(SA�); <span class="d_comment">]å error, does not match any foo <ztpan> foo(1); <span class="d_comment">]å error, matches A.foo(long) and B.foo(int) <ztpan> A.foo(1); <span class="d_comment">]å calls A.foo(long) <ztpan>} </pre> <div class="blankline"></div> �!�!p>Even�4hough <span class="d_inlinecode donthyphenate notranslate">B.foo(int)<ztpan> is a better match�4han <span class="d_inlinecode donthyphenate notranslate"> A.foo(long)</span> for <span class="d_inlinecode donthyphenate notranslate">foo(1)<ztpan>, it is an error because�4he�4wo matches are in different overload sets. �!�!y:> <div class="blankline"><u(iv> <p>Overload sets can be merged�7ith an alias declaration:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">import</span> A; <span class="d_keyword">import<ztpan> B; <span class="d_keyword">alias</span> foo = A.foo; <span class="d_keyword">alias</span> foo = B.foo; <span class="d_keyword">void</span> bar(C c) { foo(); �!�!span class="d_comment">/Xëcalls A.foo() </span> foo(1L); �!�!span class="d_comment">/Xëcalls A.foo(long) </span> foo(c); �!�!span class="d_comment">/Xëcalls B.foo(C) <ztpan> foo(1,�(SA�); <span class="d_comment">]å error, does not match any foo <ztpan> foo(1); <span class="d_comment">]å calls B.foo(int) </span> A.foo(1);�!�!span class="d_comment">/Xëcalls A.foo(long) </span>} <y:re> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="parameters" href="#parameters">Function Parameters</a></h2> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="param-storage" href="#param-storage">Parameter Storage Classes</a></h3> <div class="blankline"><u(iv> <p>Parameter storage classes are�!�!span class="d_inlinecode donthyphenate notranslate">in</span>,�!�!span class="d_inlinecode donthyphenate notranslate">out<ztpan>, <span class="d_inlinecode donthyphenate notranslate">ref</span>,�!�!span class="d_inlinecode donthyphenate notranslate">lazy</span>,�!�!span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span>. Parameters can also�4ake the type constructors <span class="d_inlinecode donthyphenate notranslate">const</span>,�!�!span class="d_inlinecode donthyphenate notranslate">immutable<ztpan>, <span class="d_inlinecode donthyphenate notranslate">shared<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">inout<ztpan>. </p> <div class="blankline"></div> �!�!p><span class="d_inlinecode donthyphenate notranslate">in<ztpan>, <span class="d_inlinecode donthyphenate notranslate">out</span>,�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">lazy</span> are mutually exclusive. The first three are used�4o denote input, output and inputwóutput parameters, respectively. For example: �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> read(<span class="d_keyword">in</span> <span class="d_keyword">char</span>[] input,�!�!span class="d_keyword">ref</span> size_t count, <span class="d_keyword">out<ztpan>�!�!span class="d_keyword">int</span> errno); <span class="d_keyword">void<ztpan> main() { size_t a = 2 2 2�([f�) �!�!span class="d_keyword">int</span> b; �!�!span class="d_keyword">int</span> r = read(<span class="d_string">"Hello 2 2 2 2orld"<ztpan>, a, b); } <y:re> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">read</span> has three parameters. <span class="d_inlinecode donthyphenate notranslate">input</span> will only be read and no reference�4o it�7ill be retained. �!�!span class="d_inlinecode donthyphenate notranslate">count<ztpan> may be read and�7ritten�4o, and�!�!span class="d_inlinecode donthyphenate notranslate">errno<ztpan>�7ill be set�4o a value from �7ithin the function.<y:> <div class="blankline"><u(iv> <p>The argument <span class="d_inlinecode donthyphenate notranslate">"Hello World"</span> gets bound�4o parameter <span class="d_inlinecode donthyphenate notranslate">input</span>, �!�!span class="d_inlinecode donthyphenate notranslate">a<ztpan> gets bound to�!�!span class="d_inlinecode donthyphenate notranslate">count<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">b<ztpan>�4o <span class="d_inlinecode donthyphenate notranslate">errno</span>. �!�!y:> <div class="blankline"><u(iv> <center><table><caption>Parameter Storage Class and Type Constructor Overview<uaption> �!�!tr><th class="donthyphenate"><b>Storage Class<u><zËh><th class="donthyphenate"><b>Description</b></th><zËr> <div class="blankline"></div> �!�!tr><td><i>none</i></td><td>The�0arameter�7ill be a mutable copy of its argument.</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">in</span><zËd><td>The parameter is an input to�4he function.</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">out<ztpan></td><td>The argument must be an lvalue,�7hich�7ill be�0assed by reference and initialized �5pon function entry�7ith the default value (<span class="d_inlinecode donthyphenate notranslate">T.init</span>) of its type. </td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref<ztpan></td><td>The�0arameter is an�!�!i>input/output</i>�0arameter, passed by reference. �!�!zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">scope</span><zËd><td> The parameter must not escape the function call (e.g. by being assigned to a global variable). �!�?gnored for any�0arameter�4hat is not a reference�4ype. �!�!zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">return<ztpan></td><td>Parameter may be returned or copied�4o the first parameter, but otherwise does not escape from the function. Such copies are required not�4o outlive the argument(s) they�7ere derived from. Ignored for parameters�7ith no references. See�!�!a href="..ztpec/memory-safe-d.html#scope-return-params">Scope Parameters</a>.<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">lazy<ztpan></td><td>argument is evaluated by the called function and not by�4he caller<zËd></tr> <div class="blankline"><u(iv> <tr><th class="donthyphenate"><b>Type Constructor<u><zËh><th class="donthyphenate"><b>Description</b></th><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">const<ztpan></td><td>argument is implicitly converted to a const�4ype<zËd></tr> <tr><td><span class="d_inlinecode donthyphenate notranslate">immutable</span><zËd><td>argument is implicitly converted�4o an immutable�4ype<zËd></tr> <tr><td><span class="d_inlinecode donthyphenate notranslate">shared<ztpan></td><td>argument is implicitly converted to a shared type</td><zËr> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">inout<ztpan></td><td>argument is implicitly converted to an inout type</td><zËr> �!�!zËable><uenter> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="in-params" href="#in-params">In Parameters<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>The parameter is an input to�4he function.�!�?nput�0arameters behave as if�4hey have �4he�!�!span class="d_inlinecode donthyphenate notranslate">const<ztpan> storage class.<y:> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> The following requires�4he�!�!span class="d_inlinecode donthyphenate notranslate">-preview=in<ztpan> switch and a compiler compliant�7ith <a href="../changelog/�(‘Ñ�)SD4.0.html#preview-in">dmd�6�(‘Ñ�)SD4.0<tæ> or higher.</div> <div class="blankline"></div> �!�!p><span class="d_inlinecode donthyphenate notranslate">in<ztpan>�0arameters also behave like�!�!a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope<ztpan></a>�0arameters.</p> <div class="blankline"></div> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">const</span>(<span class="d_keyword">int<ztpan>[]) g(<span class="d_keyword">in</span> <span class="d_keyword">int<ztpan>[] a) @safe { a[0]++; <span class="d_comment">]å Error: cannot modify const expression <ztpan> <span class="d_keyword">return</span> a;�!�!span class="d_comment">/XëError: scope�0arameter `a` may not be returned <ztpan>} </pre> </div> <div class="blankline"></div> �!�!p>Input parameters may also be�0assed by reference by the compiler. Unlike�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�0arameters,�!�!span class="d_inlinecode donthyphenate notranslate">in</span> parameters can bind to both lvalues and rvalues (such as literals).<y:> <ul><li>Types�4hat would trigger a side effect if�0assed by�6alue (such as types with a copy constructor,�0ostblit, or destructor) will always be�0assed by reference.<vîi> <li>Types�7hich cannot be copied (e.g. if�4heir copy constructor is marked as �!�!span class="d_inlinecode donthyphenate notranslate">@disable</span>)�7ill always be passed by reference.</li> <li>Dynamic arrays, classes, associative arrays, function pointers, and delegates will always be�0assed by�6alue. </li> </ul> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> If�4he�4ype of�4he�0arameter does not fall in one of�4hose categories, �7hether or not it is passed by reference is implementation defined, and�4he backend is free �4o choose�4he method that�7ill best fit�4he ABI of the platform. </div> <div class="blankline"></div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="ref-params" href="#ref-params">Ref and Out Parameters</a></h3> <div class="blankline"><u(iv> <p>By default,�0arameters take rvalue arguments. A�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�0arameter�4akes an lvalue argument, so changes to its�6alue�7ill operate on�4he caller's argument.<y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">void</span> inc(<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> x) { �8 += ± } <span class="d_keyword">void</span> seattle() { <span class="d_keyword">int<ztpan>�+ = 2 2; inc(z); <span class="d_keyword">assert</span>(z == 2 2 2); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>A�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�0arameter can also be returned by reference, see <a href="#return-ref-parameters">Return Ref Parameters.<tæ><y:> <div class="blankline"><u(iv> <p>An <span class="d_inlinecode donthyphenate notranslate">out</span> parameter is similar�4o a <span class="d_inlinecode donthyphenate notranslate">ref</span> parameter, except it is initialized by�!�!a href="..ztpec/property.html#init-vs-construction">default construction</a>�5pon function invocation.</p> <div class="blankline"></div> �!�!div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�+ero(<span class="d_keyword">out<ztpan>�!�!span class="d_keyword">int</span> x) { �!�!span class="d_keyword">assert<ztpan>(x == 0); } <span class="d_keyword">void<ztpan>�4wo(<span class="d_keyword">out</span> <span class="d_keyword">int<ztpan>�8) { x = �([f�) } <span class="d_keyword">void</span> tacoma() { �!�!span class="d_keyword">int</span> a = 0Ú0ü0¸ �+ero(a); <span class="d_keyword">assert</span>(a == 0); <span class="d_keyword">int<ztpan>�9 = 2 2; two(y); <span class="d_keyword">assert</span>(y == 2); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>For dynamic array and class object parameters, which are always�0assed by reference, <span class="d_inlinecode donthyphenate notranslate">out</span> and <span class="d_inlinecode donthyphenate notranslate">ref</span> apply only�4o the reference and not the contents. </p> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="lazy-params" href="#lazy-params">Lazy Parameters<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>An argument to a�!�!span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter is not evaluated before the function is called. The argument is only evaluated if/when�4he�0arameter is evaluated within�4he function.�?�!ence, a <span class="d_inlinecode donthyphenate notranslate">lazy<ztpan> argument can be executed 0 or more times.�!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio : writeln; <span class="d_keyword">void</span> main() { �!�!span class="d_keyword">int</span> x; 2 2.times(writeln(x++)); writeln(<span class="d_string">"-"</span>); writeln(x); } <span class="d_keyword">void<ztpan>�4imes(<span class="d_keyword">int</span> n,�!�!span class="d_keyword">lazy<ztpan>�!�!span class="d_keyword">void<ztpan> exp) { <span class="d_keyword">while<ztpan> (n--) exp(); } </pre> </div> <div class="blankline"></div> �!�!p>prints�4o the console:</p> <div class="blankline"></div> <pre class="console notranslate">0 1 �(�)− 0ª0ü0à</pre> <div class="blankline"></div> �!�!p>A <span class="d_inlinecode donthyphenate notranslate">lazy<ztpan>�0arameter cannot be an lvalue.<y:> <div class="blankline"><u(iv> <p>The�5nderlying delegate of the <span class="d_inlinecode donthyphenate notranslate">lazy<ztpan>�0arameter may be extracted by�5sing�4he�!�!span class="d_inlinecode donthyphenate notranslate">&<ztpan> operator:</p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�4est(<span class="d_keyword">lazy</span> <span class="d_keyword">int<ztpan> dg) { �!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg_ = &dg; �!�!span class="d_keyword">assert<ztpan>(dg_() == 7); <span class="d_keyword">assert</span>(dg == dg_()); } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">int<ztpan> a = 5 5 5; test(a); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>A�!�!span class="d_inlinecode donthyphenate notranslate">lazy</span> parameter of�4ype <span class="d_inlinecode donthyphenate notranslate">void<ztpan> can accept an argument of any�4ype.</p> <div class="blankline"></div> �!�!p>See Also: <a href="#lazy_variadic_functions">Lazy Variadic Functions</a></p> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="function-default-args" href="#function-default-args">Default Arguments<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Function�0arameter declarations can have default�6alues:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan> foo(<span class="d_keyword">int</span> x,�!�!span class="d_keyword">int</span> y = 0Î0Ã0È { ... } ... foo(4); �!�!span class="d_comment">/Xësame as foo(4, 2 2); <ztpan></pre> <div class="blankline"></div> �!�!p>Default parameters are resolved and semantically checked in the context of�4he function declaration.</p> <pre class="d_code notranslate"><span class="d_keyword">module<ztpan> m; <span class="d_keyword">private<ztpan>�!�!span class="d_keyword">immutable</span> <span class="d_keyword">int<ztpan> b; <span class="d_keyword">pure</span> <span class="d_keyword">void</span> g(<span class="d_keyword">int<ztpan> a = b) {} <y:re> <pre class="d_code notranslate"><span class="d_keyword">import</span> m; <span class="d_keyword">int</span> b; <span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">void<ztpan> f() { g(); �!�!span class="d_comment">/Xëok, uses m.b <ztpan>} </pre> <div class="blankline"></div> �!�!p>The attributes of the <a href="../specu0xpression.html#AssignExpression"><i>AssignExpression</i></a> are applied�7here�4he default expression is�5sed.</p> <pre class="d_code notranslate"><span class="d_keyword">module<ztpan> m; <span class="d_keyword">int<ztpan> b; <span class="d_keyword">pure</span> <span class="d_keyword">void</span> g(<span class="d_keyword">int<ztpan> a = b) {} <y:re> <pre class="d_code notranslate"><span class="d_keyword">import</span> m; <span class="d_keyword">enum<ztpan>�!�!span class="d_keyword">int</span> b = 0Ú0ü0¸ <span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">void<ztpan> f() { g(); �!�!span class="d_comment">/Xëerror, cannot access mutable global `m.b` in�0ure function <ztpan>} </pre> <div class="blankline"></div> �!�!p>See also: function�4ype aliases <a href="../specu(eclaration.html#alias-function">with default�6alues<tæ>.</p> <div class="blankline"></div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="return-ref-parameters" href="#return-ref-parameters">Return Ref Parameters<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Return ref�0arameters are used�7ith <a href="#ref-functions">ref functions</a>�4o ensure�4hat the returned reference�7ill not outlive the matching argument's lifetime. </p> <div class="blankline"></div> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> identity(<span class="d_keyword">return</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> x)" �!�!span class="d_keyword">return<ztpan>�8; <span class="d_comment">]å�0ass-through function�4hat does nothing <ztpan>} <span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> fun()" �!�!span class="d_keyword">int</span> x; �!�!span class="d_keyword">return<ztpan> identity(x); <span class="d_comment">]å Error: escaping reference�4o local variable�8 <ztpan>} <span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> gun(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">return</span> identity(x);�!�!span class="d_comment">/XëOK <ztpan>} </pre> </div> �!�!p>Returning the address of a�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�6ariable is also checked in�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> code.</p> <div class="blankline"></div> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int</span>*�0luto(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) @safe { <span class="d_keyword">return</span> &i; <span class="d_comment">]å error: returning &i escapes a reference�4o parameter i </span>} <span class="d_keyword">int<ztpan>* mars(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) @safe { <span class="d_keyword">return</span> &i; �!�!span class="d_comment">/XëOK�7ith -preview=dip1000 <ztpan>} </pre> </div> <div class="blankline"></div> <div class="panel">If a function returns <span class="d_inlinecode donthyphenate notranslate">void<ztpan>, and the first parameter is�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> or <span class="d_inlinecode donthyphenate notranslate">out</span>,�4hen all subsequent�!�!span class="d_inlinecode donthyphenate notranslate">return ref</span> parameters are considered as being assigned to the first�0arameter for lifetime checking. <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> f(<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">scope</span> <span class="d_keyword">int<ztpan>* p,�!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) @safe { p = &i; <span class="d_comment">]å OK with -preview=dip1000 </span>} <span class="d_keyword">void</span> main() @safe { �!�!span class="d_keyword">int</span> i; �!�!span class="d_keyword">int</span>*�0; f(p, i);�!�!span class="d_comment">/XëOK, lifetime of p is shorter�4han i </span> *p = 5; �!�!span class="d_keyword">assert<ztpan>(i == 5); �!�!span class="d_keyword">int</span> j; �!�!span class="d_comment">/u‹(p, j); ]å error, lifetime of p is longer than j <ztpan>} </pre> <div class="blankline"></div> The�!�!span class="d_inlinecode donthyphenate notranslate">this</span> reference parameter to a struct non-static member function is considered�4he first�0arameter. <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">private<ztpan>�!�!span class="d_keyword">int</span>*�0; �!�!span class="d_keyword">void<ztpan> f(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) <span class="d_keyword">scope<ztpan> @safe " �0 =�.�.�.amp;i;�!�!span class="d_comment">/XëOK�7ith -preview=dip1000 <ztpan> } } <span class="d_keyword">void<ztpan> main() @safe { <span class="d_keyword">int<ztpan> i; S s; s.f(i);�!�!span class="d_comment">/XëOK, lifetime of `s` is shorter�4han `i` </span> *s.p = �([f�) �!�!span class="d_keyword">assert<ztpan>(i == �(SA�); } </pre> <u(iv> <div class="blankline"><u(iv> <p>If there are multiple�!�!span class="d_inlinecode donthyphenate notranslate">return ref</span> parameters, the lifetime of the return value is the smallest lifetime of�4he corresponding arguments.<y:> <div class="blankline"><u(iv> <p>Neither�4he�4ype of�4he�!�!span class="d_inlinecode donthyphenate notranslate">return ref</span> parameter(s) nor�4he�4ype of�4he return value is considered when determining�4he lifetime of�4he return value.</p> <div class="blankline"></div> <p>It is not an error if the return�4ype does not contain any indirections.</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> mercury(<span class="d_keyword">return</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> i) { �!�!span class="d_keyword">return<ztpan> i; <span class="d_comment">]å ok </span>} <y:re> <div class="blankline"><u(iv> <p>Template functions, auto functions, nested functions and <a href="../specu0xpression.html#function_literals">lambdas<tæ> can deduce the <span class="d_inlinecode donthyphenate notranslate">return<ztpan> attribute.<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate">@safe: <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> templateFunction()(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) { <span class="d_keyword">return</span> i;�!�!span class="d_comment">/Xëok <ztpan>} <span class="d_keyword">ref</span> <span class="d_keyword">auto</span> autoFunction(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) { <span class="d_keyword">return</span> i;�!�!span class="d_comment">/Xëok <ztpan>} <span class="d_keyword">void<ztpan>�5ranus() { <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> nestedFunction(<span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) { <span class="d_keyword">return</span> i;�!�!span class="d_comment">/Xëok <ztpan> } <span class="d_keyword">auto</span> lambdaFunction = (<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> i) " �!�!span class="d_keyword">return<ztpan>�.�.�.amp;i;�!�!span class="d_comment">/Xëok <ztpan> }; } <y:re> <u(iv> <div class="blankline"><u(iv> <h4><a class="anchor" title="Permalink�4o this section" id="struct-return-methods" href="#struct-return-methods">Struct Return Methods</a></h4> <div class="blankline"><u(iv> <p>Struct non-static methods can be marked�7ith the <span class="d_inlinecode donthyphenate notranslate">return<ztpan> attribute�4o ensure a returned reference will not outlive�4he struct instance. </p> <div class="blankline"></div> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">struct<ztpan> S { �!�!span class="d_keyword">private</span> <span class="d_keyword">int<ztpan>�8; <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> get() <span class="d_keyword">return</span> { <span class="d_keyword">return</span> x;�( } <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> escape() { S s; <span class="d_keyword">return</span> s.get();�!�!span class="d_comment">/XëError: escaping reference to local�6ariable s </span>} <y:re> <u(iv> <p>The hidden <span class="d_inlinecode donthyphenate notranslate">this<ztpan> ref-parameter�4hen becomes <span class="d_inlinecode donthyphenate notranslate">return ref<ztpan>.<y:> <div class="blankline"><u(iv> <p>The�!�!span class="d_inlinecode donthyphenate notranslate">return</span> attribute can also be used�4o limit the lifetime of the returned�6alue, even�7hen the method is not <span class="d_inlinecode donthyphenate notranslate">ref</span>: �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">private<ztpan>�!�!span class="d_keyword">int</span> i; �!�!span class="d_keyword">int</span>* get()�!�!span class="d_keyword">return<ztpan> @safe =>�.�.�.amp;i; } <span class="d_keyword">void</span> f() @safe { <span class="d_keyword">int<ztpan>* p; " S s; <span class="d_keyword">int<ztpan> *q = s.get();�!�!span class="d_comment">/XëOK, q has shorter lifetime�4han s </span> �0 = s.get(); <span class="d_comment">]å error, p has longer lifetime </span> �0 = (<span class="d_keyword">new<ztpan> S).get();�!�!span class="d_comment">/XëOK, heap allocated S <ztpan> } } </pre> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="scope-parameters" href="#scope-parameters">Scope Parameters</a></h3> <div class="blankline"><u(iv> <p>A�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�0arameter of reference type must not escape�4he function call (e.g. by being assigned�4o a global�6ariable). It has no effect for non-reference�4ypes. <span class="d_inlinecode donthyphenate notranslate">scope</span> escape analysis is only done for�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> functions. For other functions <span class="d_inlinecode donthyphenate notranslate">scope</span> semantics must be manually enforced.</p> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b>�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> escape analysis is only done with�4he�!�!span class="d_inlinecode donthyphenate notranslate">-preview=dip1000</span> switch.<u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate">@safe: <span class="d_keyword">int<ztpan>* gp; <span class="d_keyword">void</span> thorin(<span class="d_keyword">scope</span> <span class="d_keyword">int<ztpan>*); <span class="d_keyword">void</span> gloin(<span class="d_keyword">int<ztpan>*); <span class="d_keyword">int<ztpan>* balin(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span>*�i, <span class="d_keyword">int<ztpan>* r) { gp =�i; <span class="d_comment">]å error, q escapes to global gp <ztpan> gp = r;�!�!span class="d_comment">/Xëok <ztpan> thorin(q);�!�!span class="d_comment">/Xëok, q does not escape thorin() <ztpan> �4horin(r); <span class="d_comment">]å ok </span> gloin(q);�!�!span class="d_comment">/Xëerror, gloin() escapes�i <ztpan> gloin(r);�!�!span class="d_comment">/Xëok�4hat gloin() escapes r </span> �!�!span class="d_keyword">return<ztpan>�i; <span class="d_comment">]å error, cannot return 'scope' q </span> <span class="d_keyword">return</span> r;�!�!span class="d_comment">/Xëok <ztpan>} </pre> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> As a <span class="d_inlinecode donthyphenate notranslate">scope</span> parameter must not escape,�4he compiler can potentially avoid heap-allocating a unique argument to a�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�0arameter. Due to�4his,�0assing an array literal, delegate literal or a�!�!a href="..ztpec/expression.html#NewExpression"><i>NewExpression<v}><tæ> to a scope�0arameter may be allowed in a �!�!span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan> context.<u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="return-scope-parameters" href="#return-scope-parameters">Return Scope Parameters</a></h3> <div class="blankline"><u(iv> <p>Parameters marked as <span class="d_inlinecode donthyphenate notranslate">return scope<ztpan>�4hat contain indirections can only escape�4hose indirections via the function's return value.</p> <div class="blankline"></div> <pre class="d_code notranslate">@safe: <span class="d_keyword">int</span>* gp; <span class="d_keyword">void<ztpan>�4horin(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span>*); <span class="d_keyword">void<ztpan> gloin(<span class="d_keyword">int</span>*); <span class="d_keyword">int</span>* balin(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">scope</span> <span class="d_keyword">int<ztpan>* p) { gp =�0; <span class="d_comment">]å error, p escapes to global gp <ztpan> �4horin(p); <span class="d_comment">]å ok,�0 does not escape�4horin() </span> gloin(p); <span class="d_comment">]å error, gloin() escapes p </span> <span class="d_keyword">return</span> p;�!�!span class="d_comment">/Xëok <ztpan>} </pre> <div class="blankline"></div> �!�!p>Class references are considered pointers�4hat are subject to�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate">@safe: <span class="d_keyword">class<ztpan> C"�( C gp; <span class="d_keyword">void<ztpan>�4horin(<span class="d_keyword">scope<ztpan> C); <span class="d_keyword">void<ztpan> gloin(C); C balin(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">scope</span> C p,�!�!span class="d_keyword">scope</span> C q, C r) { gp = p;�!�!span class="d_comment">/Xëerror,�0 escapes�4o global gp </span> gp =�i; <span class="d_comment">]å error, q escapes to global gp <ztpan> gp = r;�!�!span class="d_comment">/Xëok <ztpan> thorin(p);�!�!span class="d_comment">/Xëok, p does not escape thorin() <ztpan> �4horin(q); <span class="d_comment">]å ok </span> thorin(r);�!�!span class="d_comment">/Xëok <ztpan> gloin(p); <span class="d_comment">]å error, gloin() escapes p </span> gloin(q); <span class="d_comment">]å error, gloin() escapes q </span> gloin(r); <span class="d_comment">]å ok that gloin() escapes r <ztpan> <span class="d_keyword">return</span> p;�!�!span class="d_comment">/Xëok <ztpan> �!�!span class="d_keyword">return<ztpan>�i; <span class="d_comment">]å error, cannot return 'scope' q </span> <span class="d_keyword">return</span> r;�!�!span class="d_comment">/Xëok <ztpan>} </pre> <div class="blankline"></div> �!�!p><span class="d_inlinecode donthyphenate notranslate">return scope<ztpan> can be applied to�4he�!�!span class="d_inlinecode donthyphenate notranslate">this</span> of class and interface member functions.</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">class</span> C { C bofur() <span class="d_keyword">return</span> <span class="d_keyword">scope<ztpan>"�!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">this<ztpan>; } } </pre> <div class="blankline"></div> �!�!p>Template functions, auto functions, nested functions and �!�!a href="..ztpec/expression.html#function_literals">lambdas</a> can deduce the <span class="d_inlinecode donthyphenate notranslate">return scope<ztpan> attribute.<y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="ref-return-scope-parameters" href="#ref-return-scope-parameters">Ref Return Scope Parameters</a></h3> <div class="blankline"><u(iv> <p>It is not�0ossible to have both�!�!span class="d_inlinecode donthyphenate notranslate">return ref</span> and <span class="d_inlinecode donthyphenate notranslate">return scope<ztpan> semantics for�4he same parameter. 2 2 2 2hen a parameter is�0assed by�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> and has both the <span class="d_inlinecode donthyphenate notranslate">return<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan> storage classes, it gets <a href="#return-scope-parameters"><span class="d_inlinecode donthyphenate notranslate">return scope</span><tæ> semantics if and only if�4he�!�!span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">scope</span> keywords appear adjacent�4o each other, in�4hat order. Specifying a <span class="d_inlinecode donthyphenate notranslate">return ref<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�0arameter enables returning a reference�4o a scope pointer. �!�?n all other cases,�4he�0arameter has�!�!a href="#return-ref-parameters"><span class="d_inlinecode donthyphenate notranslate">return ref<ztpan></a> semantics and regular�!�!a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope<ztpan></a> semantics.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate">U xerxes( <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">scope</span> V v)�!�!span class="d_comment">/Xë(1) ref and return scope <ztpan>U sargon(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> �!�!span class="d_keyword">scope</span> V v)�!�!span class="d_comment">/Xë(2) return ref and scope <ztpan> <span class="d_keyword">struct<ztpan> S { �!�!span class="d_comment">/Xënote: in struct member functions, the implicit `this` parameter </span> �!�!span class="d_comment">/Xëis�0assed by `ref` <ztpan> U�8erxes() <span class="d_keyword">return</span> <span class="d_keyword">scope<ztpan>; �!�!span class="d_comment">/Xëreturn scope <ztpan> U sargon() <span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">return<ztpan>; <span class="d_comment">]å return ref, `return` comes after `scope` </span> U�8erxes() <span class="d_keyword">return</span> <span class="d_keyword">const<ztpan>�!�!span class="d_keyword">scope</span>; <span class="d_comment">]å return ref, `return` and `scope` are not adjacent <ztpan>} </pre> <div class="blankline"></div> <p>Example of combinations of�!�!span class="d_inlinecode donthyphenate notranslate">return scope</span>,�!�!span class="d_inlinecode donthyphenate notranslate">return ref</span>, and�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan> semantics:<y:> <pre class="d_code notranslate">@safe: <span class="d_keyword">int<ztpan>* globalPtr; <span class="d_keyword">struct</span> S { <span class="d_keyword">int<ztpan> val; �!�!span class="d_keyword">int</span>*�0tr; �!�!span class="d_keyword">this<ztpan>(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">scope</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span>*�0) { ptr = p;�( <span class="d_comment">]å note: `this` is�0assed by `ref` in structs </span> <span class="d_keyword">int<ztpan>* retRefA() <span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">return<ztpan>�!�!span class="d_comment">/Xëreturn-ref, scope </span> " globalPtr =�!�!span class="d_keyword">this<ztpan>.ptr; <span class="d_comment">]å disallowed, `this` is `scope` <ztpan> <span class="d_keyword">return</span> &<span class="d_keyword">this<ztpan>.val; <span class="d_comment">]å allowed, `return` means `return ref` </span> �( <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> retRefB() <span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">return<ztpan>�!�!span class="d_comment">/Xëreturn-ref, scope </span> " globalPtr =�!�!span class="d_keyword">this<ztpan>.ptr; <span class="d_comment">]å disallowed, `this` is `scope` <ztpan> <span class="d_keyword">return</span> �!�!span class="d_keyword">this<ztpan>.val; <span class="d_comment">]å allowed, `return` means `return ref` </span> �( <span class="d_keyword">int<ztpan>* retScopeA() <span class="d_keyword">return</span> <span class="d_keyword">scope<ztpan>�!�!span class="d_comment">/Xëref, return-scope </span> " �!�!span class="d_keyword">return<ztpan>�.�.�.amp;<span class="d_keyword">this</span>.val;�!�!span class="d_comment">/Xëdisallowed, escaping a reference�4o `this` <ztpan> <span class="d_keyword">return</span> <span class="d_keyword">this</span>.ptr; <span class="d_comment">]å allowed, returning a `return scope`�0ointer <ztpan> } �!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> retScopeB()�!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">scope</span> <span class="d_comment">]å ref, return-scope <ztpan> { <span class="d_keyword">return</span> <span class="d_keyword">this</span>.val; <span class="d_comment">]å disallowed, escaping a reference to `this` </span> �!�!span class="d_keyword">return<ztpan> *<span class="d_keyword">this</span>.ptr;�!�!span class="d_comment">/Xëallowed, returning a `return scope` pointer </span> �( <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span>* retRefScopeC() <span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">return<ztpan>�!�!span class="d_comment">/Xëreturn-ref, scope </span> " �!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">this<ztpan>.ptr; <span class="d_comment">]å allowed, returning a reference to a scope�0ointer <ztpan> } } <span class="d_keyword">int</span>* retRefA(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">scope<ztpan> S s) { globalPtr = s.ptr;�!�!span class="d_comment">/Xëdisallowed, `s` is `scope` <ztpan> <span class="d_keyword">return</span> &s.val; <span class="d_comment">]å allowed, returning a reference to `return ref s` </span>} <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> retRefB(<span class="d_keyword">return</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">scope</span> S s) { globalPtr = s.ptr; <span class="d_comment">]å disallowed, `s` is `scope` </span> �!�!span class="d_keyword">return<ztpan> s.val; } <span class="d_keyword">int</span>* retScopeA(<span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">scope<ztpan> S s) { <span class="d_keyword">return</span> &s.val; <span class="d_comment">]å disallowed, escaping a reference to `s` <ztpan> <span class="d_keyword">return</span> s.ptr; <span class="d_comment">]å allowed, returning a `return scope`�0ointer <ztpan>} <span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> retScopeB(<span class="d_keyword">ref</span> <span class="d_keyword">return</span> <span class="d_keyword">scope<ztpan> S s) { <span class="d_keyword">return</span> s.val; <span class="d_comment">]å disallowed, escaping a reference to `s` <ztpan> <span class="d_keyword">return</span> *s.ptr; <span class="d_comment">]å allowed, returning a `return scope`�0ointer <ztpan>} <span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan>* retRefScopeC(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span>*�0) { <span class="d_keyword">return</span> p;�!�!span class="d_comment">/Xëallowed, returning a reference�4o a scope pointer </span>} <y:re> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="pure-scope-inference" href="#pure-scope-inference">Inferred <span class="d_inlinecode donthyphenate notranslate">scope</span> parameters in <span class="d_inlinecode donthyphenate notranslate">pure<ztpan> functions</a></h3> <div class="blankline"><u(iv> When a�0arameter is not marked or inferred�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>, it may still be <span class="d_inlinecode donthyphenate notranslate">@safe</span> to assign it a�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�0ointer in a function call. The following conditions need�4o be met: <div class="blankline"><u(iv> <ul> <li>The function is <a href="#pure-functions"><span class="d_inlinecode donthyphenate notranslate">pure<ztpan></a>, hence the argument cannot be assigned to a global variable</li> <li>The function is <a href="#nothrow-functions"><span class="d_inlinecode donthyphenate notranslate">nothrow<ztpan></a>, hence the argument cannot be assigned to a�4hrown <span class="d_inlinecode donthyphenate notranslate">Exception</span> object</li> <li>None of the other parameters have mutable indirections, hence the argument cannot be assigned to a longer-lived variable</li> </ul> <div class="blankline"><u(iv> Then, the parameter is still�4reated as <span class="d_inlinecode donthyphenate notranslate">scope</span> or�!�!span class="d_inlinecode donthyphenate notranslate">return scope</span> depending on�4he return type of the function: <ul> <li>If�4he function returns by�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> or has a return�4ype that contains pointers, the argument could be returned, so it is�4reated as <span class="d_inlinecode donthyphenate notranslate">return scope<ztpan></li> <li>Otherwise,�4he argument cannot escape the function, so it is�4reated as <span class="d_inlinecode donthyphenate notranslate">scope</span><vîi> �!�!zùl> <div class="blankline"></div> <pre class="d_code notranslate">@safe: <span class="d_keyword">int</span> dereference(<span class="d_keyword">int<ztpan>* x)�!�!span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">nothrow</span>; <span class="d_keyword">int</span>* identity(<span class="d_keyword">int<ztpan>* x)�!�!span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">nothrow</span>; <span class="d_keyword">int</span>* identityThrow(<span class="d_keyword">int</span>*�8) <span class="d_keyword">pure</span>; <span class="d_keyword">void<ztpan> assignToRef(<span class="d_keyword">int</span>*�8, <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span>* escapeHatch) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow<ztpan>; <span class="d_keyword">void</span> assignToPtr(<span class="d_keyword">int<ztpan>* x,�!�!span class="d_keyword">int</span>** escapeHatch)�!�!span class="d_keyword">pure<ztpan>�!�!span class="d_keyword">nothrow</span>; <span class="d_keyword">void<ztpan> cannotAssignTo(<span class="d_keyword">int<ztpan>* x,�!�!span class="d_keyword">const</span> <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span>* noEscapeHatch) <span class="d_keyword">pure</span> <span class="d_keyword">nothrow<ztpan>; <span class="d_keyword">int</span>* globalPtr; <span class="d_keyword">int</span>*�4est(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span>*�0tr) { <span class="d_keyword">int<ztpan> result = dereference(ptr); <span class="d_comment">]å allowed, treated as `scope` <ztpan> <span class="d_keyword">int<ztpan>* ptr2 = identity(ptr); <span class="d_comment">]å allowed, treated as `return scope` </span> �!�!span class="d_keyword">int</span>*�0tr0µ0ó0Á0ü0à= identityThrow(ptr); <span class="d_comment">]å not allowed, can throw an `Exception` <ztpan> assignToRef(ptr, globalPtr);�!�!span class="d_comment">/Xënot allowed, mutable second parameter </span> assignToPtr(ptr, &globalPtr);�!�!span class="d_comment">/Xënot allowed, mutable second parameter </span> cannotAssignTo(ptr, globalPtr);�!�!span class="d_comment">/Xëallowed </span> <span class="d_keyword">return</span> ptr2; <span class="d_comment">]å not allowed, ptr2 is inferred `scope` now <ztpan>} </pre> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="udas-parameters" href="#udas-parameters">User-Defined Attributes for Parameters</a></h3> <div class="blankline"><u(iv> See also: <a href="../spectættribute.html#UserDefinedAttribute"><i>User-Defined Attributes</i></a> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="variadic" href="#variadic">Variadic Functions</a></h3> <div class="blankline"><u(iv> <p><i>Variadic Functions</i>�4ake a variable number of arguments. There are three forms:</p> <div class="blankline"></div> �!�!ol> �!�!li><a href="#c_style_variadic_functions">C-style�6ariadic functions<tæ><vîi> �!�!li><a href="#d_style_variadic_functions">Variadic functions with�4ype info</a></li> <li><a href="#typesafe_variadic_functions">Typesafe variadic functions</a></li> </ol> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h4><a class="anchor" title="Permalink�4o this section" id="c_style_variadic_functions" href="#c_style_variadic_functions">C-style Variadic Functions<tæ><vv4> <div class="blankline"></div> �!�!p>A C-style variadic function is declared with a�0arameter�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan> as the last function parameter. �!�?t has non-D linkage, such as�!�!span class="d_inlinecode donthyphenate notranslate">extern (C)</span>.</p> <div class="blankline"></div> �!�!p>To access the variadic arguments, import�4he standard library module�!�!a href="..y:hobos/core_stdc_stdarg.html"><span class="d_inlinecode donthyphenate notranslate">core.stdc.stdarg</span><tæ>. �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">import</span> core.stdc.stdarg; <span class="d_keyword">extern<ztpan> (C)�!�!span class="d_keyword">void<ztpan> dry(<span class="d_keyword">int</span> x,�!�!span class="d_keyword">int</span> y, ...);�!�!span class="d_comment">/XëC-style Variadic Function </span> <span class="d_keyword">void</span> spin() { dry(3, 4); �!�!span class="d_comment">/Xëok, no�6ariadic arguments </span> dry(3, 4, 5 5.8);�!�!span class="d_comment">/Xëok, one variadic argument </span> dry(2); �!�!span class="d_comment">/Xëerror, no argument for�0arameter�9 <ztpan>} </pre> <div class="blankline"></div> �!�!p>There must be at least one non-variadic parameter declared.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) <span class="d_keyword">int<ztpan> def(...);�!�!span class="d_comment">/Xëerror, must have at least one parameter </span><y:re> <div class="blankline"><u(iv> <p> C-style�6ariadic functions match the C calling convention for �6ariadic functions, and can call C Standard library functions like <span class="d_inlinecode donthyphenate notranslate">printf<ztpan>. </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">extern<ztpan> (C)�!�!span class="d_keyword">int</span> printf(<span class="d_keyword">const</span>(<span class="d_keyword">char</span>)*, ...); <span class="d_keyword">void</span> main() { �0rintf(<span class="d_string">"hello world\n"</span>); } </pre> <div class="blankline"></div> �!�!p>C-style variadic functions cannot be marked as�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan>.<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> wash() { rinse(3, 4, 5); �!�!span class="d_comment">/Xëfirst variadic argument is 5 <ztpan>} <span class="d_keyword">import<ztpan> core.stdc.stdarg; <span class="d_keyword">extern<ztpan> (C)�!�!span class="d_keyword">void<ztpan> rinse(<span class="d_keyword">int</span> x,�!�!span class="d_keyword">int</span> y, ...) { va_list args; va_start(args,�9);�!�!span class="d_comment">/Xëy is�4he last named parameter </span> �!�!span class="d_keyword">int</span> z; �6a_arg(args, z); <span class="d_comment">]å�+ is set to 5 <ztpan> va_end(args); } </pre> <div class="blankline"></div> <div class="blankline"></div> <h4><a class="anchor"�4itle="Permalink to�4his section" id="d_style_variadic_functions" href="#d_style_variadic_functions">D-style Variadic Functions</a></h4> <div class="blankline"><u(iv> <p>D-style�6ariadic functions have D linkage and�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan> as the last �0arameter.<y:> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">...<ztpan> can be the only�0arameter.<y:> <div class="blankline"><u(iv> <p>If there are parameters�0receding�4he�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan>�0arameter, there must be a comma separating�4hem from�4he�!�!span class="d_inlinecode donthyphenate notranslate">...<ztpan>.<y:> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> If�4he comma is ommitted, it is a <a href="#variadic">TypeSafe Variadic Function</a>.<u(iv> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> abc(<span class="d_keyword">char<ztpan> c, ...); <span class="d_comment">]å one required parameter: c <ztpan><span class="d_keyword">int<ztpan> def(...); �!�!span class="d_comment">/Xëno required parameters <ztpan><span class="d_keyword">int<ztpan> ghi(<span class="d_keyword">int</span> i ...); <span class="d_comment">]å a�4ypesafe variadic function </span><span class="d_comment">/v}nt boo(, ...); � Xëerror </span><y:re> <u(iv> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <p>Two hidden arguments are passed�4o the function:<y:> <div class="blankline"><u(iv> <ul> <li><span class="d_inlinecode donthyphenate notranslate">void*� argptr</span><vîi> �!�!li><span class="d_inlinecode donthyphenate notranslate">TypeInfo[]� arguments<ztpan></li> </ul> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">_argptr<ztpan> is a reference to�4he first of the variadic arguments. To access the variadic arguments, import�!�!a href="..y:hobos/core_vararg.html"><span class="d_inlinecode donthyphenate notranslate">core.vararg</span><tæ>. Use�!�!span class="d_inlinecode donthyphenate notranslate">_argptr<ztpan> in conjunction with�!�!span class="d_inlinecode donthyphenate notranslate">core.va_arg<ztpan>:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">import</span> core.vararg; <span class="d_keyword">void</span> test() { foo(3, 4, 5); �!�!span class="d_comment">/Xëfirst variadic argument is 5 <ztpan>} @system�!�!span class="d_keyword">void<ztpan> foo(<span class="d_keyword">int</span> x,�!�!span class="d_keyword">int</span> y, ...) { <span class="d_keyword">int<ztpan>�+ =�6a_arg!<span class="d_keyword">int<ztpan>(_argptr);�!�!span class="d_comment">/Xëz is set�4o 5 and _argptr is advanced </span> <span class="d_comment">]å�4o the next argument </span>} <y:re> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">_arguments</span> gives the number of arguments and the <span class="d_inlinecode donthyphenate notranslate">typeid<ztpan> of each, enabling�4ype safety�4o be checked at run time.<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">import</span> std.stdio; <span class="d_keyword">void</span> main() { Foo f =�!�!span class="d_keyword">new</span> Foo(); Bar b =�!�!span class="d_keyword">new</span> Bar(); writefln(<span class="d_string">"%s"</span>, f); �0rintargs(1, �(l4�) 2 2L, 2 2 2.5, f, b); } <span class="d_keyword">class<ztpan> Foo"�!�!span class="d_keyword">int</span> x = 0Ú0ü0¸�( <span class="d_keyword">class</span> Bar { <span class="d_keyword">long</span> y = 4;�( <span class="d_keyword">import</span> core.vararg; @system <span class="d_keyword">void</span> printargs(<span class="d_keyword">int<ztpan>�8, ...) { �7ritefln(<span class="d_string">"%d arguments"<ztpan>, _arguments.length); <span class="d_keyword">for<ztpan> (<span class="d_keyword">int<ztpan> i = 0; i <� arguments.length; i++) " �7riteln(_arguments[i]); <span class="d_keyword">if</span> (_arguments[i] == <span class="d_keyword">typeid</span>(<span class="d_keyword">int<ztpan>)) " �!�!span class="d_keyword">int</span> j = va_arg�Z<span class="d_keyword">int<ztpan>)(_argptr); writefln(<span class="d_string">"\t%d"</span>, j); �( �!�!span class="d_keyword">else<ztpan>�!�!span class="d_keyword">if<ztpan> (_arguments[i] ==�!�!span class="d_keyword">typeid<ztpan>(<span class="d_keyword">long<ztpan>)) " �!�!span class="d_keyword">long<ztpan> j =�6a_arg!(<span class="d_keyword">long<ztpan>)(_argptr); writefln(<span class="d_string">"\t%d"</span>, j); �( �!�!span class="d_keyword">else<ztpan>�!�!span class="d_keyword">if<ztpan> (_arguments[i] ==�!�!span class="d_keyword">typeid<ztpan>(<span class="d_keyword">double<ztpan>)) " �!�!span class="d_keyword">double<ztpan> d =�6a_arg!(<span class="d_keyword">double<ztpan>)(_argptr); writefln(<span class="d_string">"\t%g"</span>, d); �( �!�!span class="d_keyword">else<ztpan>�!�!span class="d_keyword">if<ztpan> (_arguments[i] ==�!�!span class="d_keyword">typeid<ztpan>(Foo)) " Foo f =�6a_arg!(Foo)(_argptr); writefln(<span class="d_string">"\t%s"</span>, f); �( �!�!span class="d_keyword">else<ztpan>�!�!span class="d_keyword">if<ztpan> (_arguments[i] ==�!�!span class="d_keyword">typeid<ztpan>(Bar)) " Bar b =�6a_arg!(Bar)(_argptr); writefln(<span class="d_string">"\t%s"</span>, b); �( �!�!span class="d_keyword">else<ztpan> �!�!span class="d_keyword">assert<ztpan>(0); �( } <y:re> <u(iv> <div class="blankline"><u(iv> which prints: <div class="blankline"><u(iv> <pre class="d_code notranslate">0x00870FE0 5 arguments <span class="d_keyword">int</span> �(�)<span class="d_keyword">long</span> 0ª0ü0à<span class="d_keyword">double</span> 4.5 Foo 0x00870FE0 Bar 0x0SA70FD0 </pre> <div class="blankline"></div> �!�!p>D-style variadic functions cannot be marked as�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan>.<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h4><a class="anchor" title="Permalink�4o this section" id="typesafe_variadic_functions" href="#typesafe_variadic_functions">Typesafe Variadic Functions</a></h4> <div class="blankline"><u(iv> <p>A�4ypesafe variadic function has D linkage and a variadic �0arameter declared as either an array or a class. The array or class is constructed from the arguments, and is passed as an array or class object. </p> <div class="blankline"></div> �!�!p>For dynamic arrays:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> sum(<span class="d_keyword">int</span>[] ar ...) <span class="d_comment">]å�4ypesafe variadic function </span>{ �!�!span class="d_keyword">int</span> s; �!�!span class="d_keyword">foreach</span> (<span class="d_keyword">int</span> x; ar) s += x; �!�!span class="d_keyword">return<ztpan> s; } <span class="d_keyword">import<ztpan> std.stdio; <span class="d_keyword">void<ztpan> main() { writeln(stan()); <span class="d_comment">]å 5 5 <ztpan> writeln(ollie()); <span class="d_comment">]å 15 </span>} <span class="d_keyword">int<ztpan> stan() { <span class="d_keyword">return</span> sum(1, 2, 0Î0Ã0È + sum(); <span class="d_comment">]å returns 5 5+0 <ztpan>} <span class="d_keyword">int</span> ollie() { <span class="d_keyword">int<ztpan>[3] ii = [4, 5, 6]; <span class="d_keyword">return</span> sum(ii); �!�!span class="d_comment">/Xëreturns ¬ <ztpan>} </pre> � </div> <div class="blankline"></div> �!�!p>For static arrays,�4he number of arguments must match the array dimension.</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> sum(<span class="d_keyword">int<ztpan>[3] ar ...) <span class="d_comment">]å�4ypesafe variadic function </span>{ �!�!span class="d_keyword">int</span> s; �!�!span class="d_keyword">foreach</span> (<span class="d_keyword">int</span> x; ar) s += x; �!�!span class="d_keyword">return<ztpan> s; } <span class="d_keyword">int</span> frank() { <span class="d_keyword">return</span> sum(�(l4�) 2 2); <span class="d_comment">]å error, need 2 2�6alues for array </span> �!�!span class="d_keyword">return<ztpan> sum(1, �(l4�) 2 2);�!�!span class="d_comment">/Xëreturns 6 </span>} <span class="d_keyword">int<ztpan> dave() { <span class="d_keyword">int<ztpan>[3] ii = [4, 5, 6]; <span class="d_keyword">int<ztpan>[] jj = ii; <span class="d_keyword">return</span> sum(ii);�!�!span class="d_comment">/Xëreturns ¬ <ztpan> <span class="d_keyword">return</span> sum(jj);�!�!span class="d_comment">/Xëerror,�4ype mismatch <ztpan>} </pre> <div class="blankline"></div> �!�!div class="keyval Deprecated"><span class="key keyDeprecated">Deprecated:<ztpan>�!�!div class="val�6alDeprecated">For class objects:</div></div> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan>�4esla(<span class="d_keyword">int</span> x, C c ...) { <span class="d_keyword">return</span> x + c.x; } <span class="d_keyword">class<ztpan> C { �!�!span class="d_keyword">int</span> x; string s; <span class="d_keyword">this</span>(<span class="d_keyword">int<ztpan>�8, string s) { <span class="d_keyword">this</span>.x = x; �!�!span class="d_keyword">this<ztpan>.s = s; } } <span class="d_keyword">void<ztpan> edison() { C g = <span class="d_keyword">new<ztpan> C(3, <span class="d_string">"abc"</span>); tesla(1, c); �!�!span class="d_comment">/Xëok, since c is an instance of C </span> �4esla(1, 4,�!�!span class="d_string">"def"<ztpan>); <span class="d_comment">]å ok </span> �4esla(1, 5); <span class="d_comment">]å error, no matching constructor for C </span>} <y:re> <div class="blankline"><u(iv> <p>The lifetime of�4he�6ariadic class object or array instance ends at�4he end of the function. </p> <div class="blankline"></div> <pre class="d_code notranslate">C orville(C c ...) { <span class="d_keyword">return</span> c; �!�!span class="d_comment">/Xëerror, c instance contents invalid after return </span>} <span class="d_keyword">int<ztpan>[]�7ilbur(<span class="d_keyword">int<ztpan>[] a ...) { <span class="d_keyword">return</span> a; �!�!span class="d_comment">/Xëerror, array contents invalid after return <ztpan> <span class="d_keyword">return</span> a[0..1];�!�!span class="d_comment">/Xëerror, array contents invalid after return <ztpan> <span class="d_keyword">return</span> a.dup; �!�!span class="d_comment">/Xëok, since copy is made <ztpan>} </pre> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b>�4he�6ariadic object or array instance may be constructed on�4he stack.<u(iv> <div class="blankline"><u(iv> <p>For other�4ypes, the argument is passed by value.</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> neil(<span class="d_keyword">int</span> i ...) { �!�!span class="d_keyword">return<ztpan> i; } <span class="d_keyword">void<ztpan> buzz() { neil(3); <span class="d_comment">]å returns 2 2 <ztpan> neil(3, 4); <span class="d_comment">]å error, too many arguments <ztpan> <span class="d_keyword">int<ztpan>[]�8; neil(x); <span class="d_comment">]å error, type mismatch </span>} <y:re> <div class="blankline"><u(iv> <h4><a class="anchor" title="Permalink�4o this section" id="lazy_variadic_functions" href="#lazy_variadic_functions">Lazy Variadic Functions</a></h4> <div class="blankline"><u(iv> <p>If the variadic�0arameter of a function is an array of delegates with no parameters, then each of�4he arguments�7hose�4ype does not match�4hat of�4he delegate is converted�4o a delegate of that�4ype. �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> hal(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>()[] dgs ...); <span class="d_keyword">void<ztpan> dave() { <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">delegate<ztpan>() dg; hal(1, 0Ñ0ü0»0ó0Èx, dg,�!�!span class="d_keyword">cast<ztpan>(<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>())<span class="d_keyword">null</span>); <span class="d_comment">]å (1) <ztpan> hal("�!�!span class="d_keyword">return<ztpan> 1; },"�!�!span class="d_keyword">return<ztpan> 2 2+x; }, dg,�!�!span class="d_keyword">null<ztpan> ); <span class="d_comment">]å same as (1) <ztpan>} </pre> <div class="blankline"></div> �!�!p>The variadic delegate array differs from�5sing a lazy variadic array. With�4he latter each array element access would evaluate every array element. With�4he former, only the element being accessed�7ould be evaluated.</p> <div class="blankline"></div> �!�!div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">import<ztpan> std.stdio; <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">int<ztpan>�8; ming(++x, ++x); �!�!span class="d_keyword">int</span> y; flash(++y, ++y); } <span class="d_comment">/Xëlazy�6ariadic array </span><span class="d_keyword">void<ztpan> ming(<span class="d_keyword">lazy</span> <span class="d_keyword">int<ztpan>[] arr...) { �7riteln(arr[0]); <span class="d_comment">]å 1 <ztpan> writeln(arr[o);�!�!span class="d_comment">/Xë4 </span>} <span class="d_comment">]å�6ariadic delegate array <ztpan><span class="d_keyword">void</span> flash(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>()[] arr ...) { �7riteln(arr[0]()); <span class="d_comment">]å 1 <ztpan> writeln(arr[o());�!�!span class="d_comment">/Xë�(�)</span>} <y:re> <u(iv> <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b> Use�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�7hen declaring the array of delegates �0arameter. This�7ill prevent a closure being generated for the delegate, as�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan> means�4he delegate will not escape the function.<u(iv> <div class="blankline"><u(iv> <span id="this-reference"><a class="anchor" title="Permalink�4o this section" id="" href="#"><tæ><ztpan> <h3><a class="anchor"�4itle="Permalink to�4his section" id="hidden-parameters" href="#hidden-parameters">Hidden Parameters<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!ul> �!�!li> Non-static member functions all have a hidden�0arameter called the <a href="../specu0xpression.html#this"><span class="d_inlinecode donthyphenate notranslate">this</span> reference<tæ>,�7hich refers to�4he object for which the function is called. </li> <li>D-style variadic functions have <a href="#d_style_variadic_functions">hidden�0arameters<tæ>.</li> <li> Functions with�!�!span class="d_inlinecode donthyphenate notranslate">Objective-C<ztpan> linkage have an additional hidden, unnamed,�0arameter�7hich is the selector it was called�7ith. �!�!vîi> �!�!zùl> <div class="blankline"></div> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="refscopereturn" href="#refscopereturn">Ref Scope Return Cases</a></h2> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="rsr_definitions" href="#rsr_definitions">Definitions</a></h3> <div class="blankline"><u(iv> <center><table><caption>Definitions<uaption> �!�!tr><th class="donthyphenate"><b>Term</b></th><th class="donthyphenate"><b>Description<u><zËh></tr> <tr><td>I<zËd><td>type�4hat contains no indirections</td><zËr> �!�!tr><td>P</td><td>type that contains indirections</td><zËr> �!�!tr><td>X</td><td>type that may or may not contain indirections</td><zËr> �!�!tr><td>p</td><td>parameter of type P</td><zËr> �!�!tr><td>i</td><td>parameter of type�!�?</td><zËr> �!�!tr><td>ref</td><td><span class="d_inlinecode donthyphenate notranslate">ref<ztpan> or <span class="d_inlinecode donthyphenate notranslate">out</span> parameter<zËd></tr> <div class="blankline"><u(iv> <tr><td>returned</td><td>returned via the <span class="d_inlinecode donthyphenate notranslate">return<ztpan> statement</td><zËr> �!�!tr><td>escaped</td><td>stored in a global or other memory not in�4he function’s stack frame<zËd></tr> </table></center> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="rsr_classification" href="#rsr_classification">Classification<tæ><vv0Ü0ë0È <div class="blankline"></div> <p>A parameter must be in one of the following states:<y:> <div class="blankline"><u(iv> <center><table><caption>Classification</caption> <tr><th class="donthyphenate"><b>Term<u><zËh><th class="donthyphenate"><b>Description</b></th><zËr> �!�!tr><td>None<zËd><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned or escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>ReturnScope</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be returned but not escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>Scope</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be neither returned nor escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>Ref</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be returned or escaped, �!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> may not be returned nor escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>ReturnRef</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be returned or escaped, �!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> may be returned but not escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>RefScope<zËd><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be neither returned nor escaped, �!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> may not be returned nor escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>ReturnRef-Scope</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be neither returned nor escaped, <span class="d_inlinecode donthyphenate notranslate">ref</span> may be returned but not escaped<zËd></tr> <div class="blankline"><u(iv> <tr><td>Ref-ReturnScope<zËd><td> <span class="d_inlinecode donthyphenate notranslate">p</span> may be returned but not escaped, �!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> may not be returned nor escaped</td><zËr> <div class="blankline"></div> �!�!tr><td>ReturnRef-ReturnScope</td><td> �!�!span class="d_inlinecode donthyphenate notranslate">p<ztpan> may be returned but not escaped, <span class="d_inlinecode donthyphenate notranslate">ref</span> may be returned but not escaped. This isn't expressible with�4he current syntax and so is not allowed.</td><zËr> �!�!zËable><uenter> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="rsr_mapping" href="#rsr_mapping">Mapping Syntax Onto Classification</a></h3> <div class="blankline"><u(iv> <p>The juxtaposition of <span class="d_inlinecode donthyphenate notranslate">return<ztpan> immediately�0receding�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan> means ReturnScope. Otherwise,�!�!span class="d_inlinecode donthyphenate notranslate">return</span> and <span class="d_inlinecode donthyphenate notranslate">ref</span> in any�0osition means ReturnRef.</p> <div class="blankline"></div> �!�!center><table><caption>Mapping</caption> <tr><th class="donthyphenate"><b>Example</b></th><th class="donthyphenate"><b>Classification</b></th><th class="donthyphenate"><b>Comments</b></th><zËr> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(P p)</span><zËd><td> None</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(scope P p)</span><zËd><td> Scope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return scope P p)</span><zËd><td> ReturnScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(return scope P p)</span><zËd><td> Scope<zËd><td> The <span class="d_inlinecode donthyphenate notranslate">return<ztpan> is dropped because the return�4ype <span class="d_inlinecode donthyphenate notranslate">I</span> contains no pointers.<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return P p)</span><zËd><td> ReturnScope<zËd><td> Makes no sense�4o have�!�!span class="d_inlinecode donthyphenate notranslate">return</span> without <span class="d_inlinecode donthyphenate notranslate">scope</span>.</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(return P�0)<ztpan></td><td> Scope</td><td> The�!�!span class="d_inlinecode donthyphenate notranslate">return</span> is dropped because�4he return type�!�!span class="d_inlinecode donthyphenate notranslate">I<ztpan> contains no�0ointers.</td><zËr> <div class="blankline"></div> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref P p)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref scope P�0)<ztpan></td><td> RefScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return scope P p)</span><zËd><td> Ref-ReturnScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(return ref scope P p)</span><zËd><td> ReturnRef-Scope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return scope P p)</span><zËd><td> RefScope</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return P�0)<ztpan></td><td> ReturnRef</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return P�0)<ztpan></td><td> Ref</td><zËr> <div class="blankline"></div> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(P p)</span><zËd><td> None</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(scope P p)</span><zËd><td> Scope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return scope P p)</span><zËd><td> ReturnScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return P p)</span><zËd><td> ReturnScope<zËd><td> Makes no sense�4o have�!�!span class="d_inlinecode donthyphenate notranslate">return</span> without <span class="d_inlinecode donthyphenate notranslate">scope</span>.</td><zËr> <div class="blankline"></div> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref P p)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref scope P�0)<ztpan></td><td> RefScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return scope P p)</span><zËd><td> Ref-ReturnScope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return ref scope P p)</span><zËd><td> ReturnRef-Scope<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return P p)</span><zËd><td> ReturnRef<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(I i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(scope�!�? i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(return scope I i)</span><zËd><td> None</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(return�!�? i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref�!�? i)<ztpan></td><td> Ref</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref scope I i)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">X foo(ref return scope I i)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">P foo(ref return I i)</span><zËd><td> ReturnRef<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">I foo(ref return I i)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(I i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(scope�!�? i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return scope I i)</span><zËd><td> None</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(return�!�? i)<ztpan></td><td> None<zËd></tr> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref�!�? i)<ztpan></td><td> Ref</td><zËr> <div class="blankline"></div> �!�!tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref scope I i)</span><zËd><td> Ref<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return scope I i)</span><zËd><td> ReturnRef<zËd></tr> <div class="blankline"><u(iv> <tr><td><span class="d_inlinecode donthyphenate notranslate">ref X foo(ref return I i)</span><zËd><td> ReturnRef<zËd></tr> </table></center> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="rsr_memberfunctions" href="#rsr_memberfunctions">Member Functions<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Member functions are rewritten as if�4he�!�!span class="d_inlinecode donthyphenate notranslate">this</span> parameter is�4he first �0arameter of a non-member function, �!�!y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { X foo(); } <y:re> <div class="blankline"><u(iv> <p>is treated as:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate">X foo(<span class="d_keyword">ref<ztpan> S); <y:re> <div class="blankline"><u(iv> <p>and:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> C" X foo() } <y:re> <div class="blankline"><u(iv> <p>is treated as:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate">X foo(P) <y:re> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="rsr_PandRef" href="#rsr_PandRef">P and ref</a></h3> <div class="blankline"><u(iv> <p>The rules account for switching between�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> and P, such as:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span>* foo(<span class="d_keyword">return<ztpan>�!�!span class="d_keyword">ref</span> <span class="d_keyword">int<ztpan> i) { <span class="d_keyword">return</span> &i; } <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan>* p)"�!�!span class="d_keyword">return<ztpan> *p;�( <y:re> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="rsr_covariance" href="#rsr_covariance">Covariance<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Covariance means a�0arameter�7ith restrictions can be converted to a�0arameter�7ith fewer restrictions. This is deducible from�4he description of each state. </p> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b>�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan> is not covariant with non-<span class="d_inlinecode donthyphenate notranslate">ref<ztpan>, so�4hose entries are omitted from the table for simplicity. </div> <div class="blankline"></div> �!�!center><table><caption>Covariance<uaption> �!�!tr><th class="donthyphenate"><b>From\To<u><zËh><th class="donthyphenate"><b> None</b></th><th class="donthyphenate"><b> ReturnScope<u><zËh><th class="donthyphenate"><b>Scope</b></th><zËr> �!�!tr><td>None<zËd><td> �.�.�.#10004;<zËd><td> �!�!zËd><td> </td><zËr> �!�!tr><td>ReturnScope</td><td> �.�.�.#10004;<zËd><td>✔ �!�!zËd><td> </td><zËr> �!�!tr><td>Scope</td><td> �.�.�.#10004;<zËd><td>✔ �!�!zËd><td>✔</td><zËr> �!�!zËable><uenter> <div class="blankline"></div> �!�!center><table><caption>Ref Covariance<uaption> �!�!tr><th class="donthyphenate"><b>From\To<u><zËh><th class="donthyphenate"><b> Ref </b></th><th class="donthyphenate"><b>ReturnRef<u><zËh><th class="donthyphenate"><b>RefScope<u><zËh><th class="donthyphenate"><b>ReturnRef-Scope</b></th><th class="donthyphenate"><b>Ref-ReturnScope<u><zËh></tr> <tr><td>Ref<zËd><td> ✔</td><td>✔ </td><td> �!�!zËd><td> �!�!zËd><td> �!�!zËd></tr> <tr><td>ReturnRef<zËd><td> </td><td>✔ </td><td> �!�!zËd><td> �!�!zËd><td> �!�!zËd></tr> <tr><td>RefScope</td><td> ✔</td><td>✔ </td><td>✔<zËd><td>✔ �!�!zËd><td>�.�.�.#10004;<zËd></tr> <tr><td>ReturnRef-Scope<zËd><td> </td><td>✔ </td><td> �!�!zËd><td>✔ �!�!zËd><td> �!�!zËd></tr> <tr><td>Ref-ReturnScope<zËd><td> ✔</td><td>✔ </td><td> �!�!zËd><td> �!�!zËd><td>�.�.�.#10004;<zËd></tr> </table></center> <div class="blankline"><u(iv> <p>For example, <span class="d_inlinecode donthyphenate notranslate">scope</span> matches all non-ref parameters, and <span class="d_inlinecode donthyphenate notranslate">ref scope</span> matches all ref parameters.<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<span id="Local Variables"><a class="anchor"�4itle="Permalink to�4his section" id="local-variables" href="#local-variables">Local Variables<tæ><ztpan></h2> <div class="blankline"><u(iv> <p>Local�6ariables are declared within�4he scope of a function. Function�0arameters are included.<y:> <div class="blankline"><u(iv> <p>A local�6ariable cannot be read�7ithout first assigning it a value.</p> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> The implementation may not always be able �4o detect�4hese cases. </div> <div class="blankline"></div> �!�!p>The address of or reference to a local non-static variable cannot be returned from�4he function. �!�!y:> <div class="blankline"><u(iv> <p>A local�6ariable and a label in�4he same function cannot have�4he same name. </p> <div class="blankline"></div> �!�!p>A local variable cannot hide another local �6ariable in�4he same function. </p> <div class="blankline"></div> �!�!div class="spec-boxes rationale"><b>Rationale:</b>�7henever this is done it often is a bug or at least looks like a bug. �!�!u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">double<ztpan> func(<span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">int<ztpan>�8; <span class="d_comment">]å error, hides previous definition of�8 <ztpan> <span class="d_keyword">double</span> y; " �!�!span class="d_keyword">char<ztpan>�9; �!�!span class="d_comment">/Xëerror, hides�0revious definition of y </span> �!�!span class="d_keyword">int</span> z; �( " �!�!span class="d_keyword">wchar</span> z;�!�!span class="d_comment">/XëOk, previous�+ is out of scope <ztpan> } z: �!�!span class="d_comment">/Xëerror,�+ is a local variable and a label <ztpan> <span class="d_keyword">return</span> y; <span class="d_comment">]å error, returning ref to local <ztpan>} </pre> <div class="blankline"></div> <div class="blankline"></div> <h3><span id="Local Static Variables"><a class="anchor"�4itle="Permalink to�4his section" id="local-static-variables" href="#local-static-variables">Local Static Variables</a></span><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Local variables in functions declared as�!�!span class="d_inlinecode donthyphenate notranslate">static</span>,�!�!span class="d_inlinecode donthyphenate notranslate">shared static<ztpan> or <span class="d_inlinecode donthyphenate notranslate">__gshared</span> are statically allocated rather than being allocated on the stack. The lifetime of�!�!span class="d_inlinecode donthyphenate notranslate">__gshared<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">shared static<ztpan>�6ariables begins when�4he function is first executed and ends�7hen the program ends. The lifetime of <span class="d_inlinecode donthyphenate notranslate">static<ztpan>�6ariables begins when�4he function is first executed within�4he�4hread and ends�7hen that�4hread terminates. </p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">import<ztpan> std.stdio :�7riteln; <span class="d_keyword">void<ztpan> foo() { �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> n; �!�!span class="d_keyword">if<ztpan> (++n == 100) writeln(<span class="d_string">"called 100�4imes"<ztpan>); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>The initializer for a static variable must be evaluatable at compile time. There are no static constructors or static destructors for static local variables. �!�!y:> <div class="blankline"><u(iv> <p>Although static�6ariable name�6isibility follows the usual scoping rules,�4he names of them must be�5nique within a�0articular function. </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan> main() { { <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan>�8; } { <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan>�8; } <span class="d_comment">]å error <ztpan> { <span class="d_keyword">int<ztpan> i; } { <span class="d_keyword">int<ztpan> i; } <span class="d_comment">]å ok </span>} <y:re> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="nested" href="#nested">Nested Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>Functions may be nested within other functions:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> bar(<span class="d_keyword">int</span> a) { �!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan> b) { <span class="d_keyword">int<ztpan> abc()"�!�!span class="d_keyword">return<ztpan> 1; } �!�!span class="d_keyword">return<ztpan> b + abc(); } <span class="d_keyword">return</span> foo(a); } <span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">int<ztpan> i = bar(3);�!�!span class="d_comment">/Xëi is assigned 4 </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <p>Nested functions can be accessed only if the name is in scope.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> foo() { <span class="d_keyword">void</span> A() { B();�!�!span class="d_comment">/Xëerror, B() is forward referenced <ztpan> C();�!�!span class="d_comment">/Xëerror, C�5ndefined <ztpan> } <span class="d_keyword">void</span> B() { A();�!�!span class="d_comment">/Xëok, in scope <ztpan> <span class="d_keyword">void</span> C() { <span class="d_keyword">void</span> D() { A(); <span class="d_comment">]å ok </span> B(); �!�!span class="d_comment">/Xëok <ztpan> C(); <span class="d_comment">]å ok </span> D(); �!�!span class="d_comment">/Xëok <ztpan> } } } A();�!�!span class="d_comment">/Xëok <ztpan> B();�!�!span class="d_comment">/Xëok <ztpan> C();�!�!span class="d_comment">/Xëerror, C�5ndefined <ztpan>} </pre> <div class="blankline"></div> and: <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> bar(<span class="d_keyword">int</span> a) { �!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan> b) { <span class="d_keyword">return</span> b + ±�( �!�!span class="d_keyword">int</span> abc(<span class="d_keyword">int<ztpan> b) { <span class="d_keyword">return</span> foo(b); } <span class="d_comment">]å ok </span> �!�!span class="d_keyword">return<ztpan> foo(a); } <span class="d_keyword">void</span> test() { �!�!span class="d_keyword">int</span> i = bar(0Î0Ã0È; <span class="d_comment">]å ok </span> �!�!span class="d_keyword">int</span> j = bar.foo(0Î0Ã0È; <span class="d_comment">]å error, bar.foo not visible </span>} <y:re> <div class="blankline"><u(iv> <p>Nested functions have access to�4he�6ariables and other symbols defined by the lexically enclosing function. This access includes both the ability to read and write them. </p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int<ztpan> a) { <span class="d_keyword">int<ztpan> c = 2 2; �!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan> b) { b += c; <span class="d_comment">]å 2 2 2 is added to b <ztpan> c++; <span class="d_comment">]å bar.c is now 5 </span> �!�!span class="d_keyword">return<ztpan> b + c; <span class="d_comment">]å 1�(N��)is returned </span> �( c = 2 2 2; <span class="d_keyword">int<ztpan> i = foo(a);�!�!span class="d_comment">/Xëi is set�4o  <ztpan> <span class="d_keyword">return</span> i + c; �!�!span class="d_comment">/Xëreturns  <ztpan>} <span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">int<ztpan> i = bar(3);�!�!span class="d_comment">/Xëi is assigned  <ztpan>} </pre> </div> <div class="blankline"></div> �!�!p>This access can span multiple nesting levels:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> bar(<span class="d_keyword">int</span> a) { �!�!span class="d_keyword">int</span> c = 0Ú0ü0¸ <span class="d_keyword">int<ztpan> foo(<span class="d_keyword">int</span> b) " �!�!span class="d_keyword">int</span> abc() { <span class="d_keyword">return</span> c; �!�!span class="d_comment">/Xëaccess bar.c <ztpan> } <span class="d_keyword">return</span> b + c + abc(); �( �!�!span class="d_keyword">return<ztpan> foo(3); } <y:re> <u(iv> <div class="blankline"><u(iv> <p>Static nested functions cannot access any stack�6ariables of any lexically enclosing function, but can access static variables. This is analogous�4o how static member functions behave. </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> bar(<span class="d_keyword">int<ztpan> a) { <span class="d_keyword">int<ztpan> c; <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan> d; �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> foo(<span class="d_keyword">int<ztpan> b) { b = d; <span class="d_comment">]å ok </span> b = c; �!�!span class="d_comment">/Xëerror, foo() cannot access frame of bar() </span> �!�!span class="d_keyword">return<ztpan> b + 1; } <span class="d_keyword">return</span> foo(a); } </pre> <div class="blankline"></div> �!�!p>Functions can be nested within member functions:</p> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">struct<ztpan> Foo { �!�!span class="d_keyword">int</span> a; <span class="d_keyword">int<ztpan> bar() " �!�!span class="d_keyword">int</span> c; <span class="d_keyword">int<ztpan> foo() " �!�!span class="d_keyword">return<ztpan> c + a; } <span class="d_keyword">return</span> 0; �( } <y:re> <u(iv> <div class="blankline"><u(iv> <p>Nested functions always have the D function linkage�4ype. �!�!y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="nested-declaration-arder" href="#nested-declaration-order">Declaration Order</a></h3> <div class="blankline"><u(iv> <p>Unlike module level declarations, declarations within function scope are processed in order. This means�4hat two nested functions cannot mutually call each other: </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">void</span> foo() { bar();�(�!�!span class="d_comment">/Xëerror, bar not defined <ztpan> <span class="d_keyword">void</span> bar() { foo();�(�!�!span class="d_comment">/Xëok <ztpan>} </pre> <div class="blankline"></div> �!�!p>There are several workarounds for this limitation:</p> <div class="blankline"></div> <ul><div class="blankline"></div> �!�!li>Declare�4he functions�4o be static members of a nested struct:<vîi> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">static</span> <span class="d_keyword">struct</span> S { <span class="d_keyword">static</span> <span class="d_keyword">void</span> foo() { bar();�(�!�!span class="d_comment">/Xëok <ztpan> <span class="d_keyword">static</span> <span class="d_keyword">void</span> bar() { foo();�(�!�!span class="d_comment">/Xëok <ztpan> } S.foo(); �!�!span class="d_comment">/Xëcompiles (but note�4he infinite runtime loop) </span>} <y:re> <div class="blankline"><u(iv> <li>Declare one or more of�4he functions�4o be function templates even if they�4ake no specific template arguments:<vîi> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">void</span> foo()() { bar();�(�!�!span class="d_comment">/Xëok (foo is a function template) </span> �!�!span class="d_keyword">void<ztpan> bar() " foo(); } <span class="d_comment">]å ok </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <li>Declare the functions inside of a mixin template:<vîi> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">mixin</span> <span class="d_keyword">template</span> T() { <span class="d_keyword">void</span> foo() { bar();�(�!�!span class="d_comment">/Xëok <ztpan> <span class="d_keyword">void</span> bar() { foo();�(�!�!span class="d_comment">/Xëok <ztpan>} <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">mixin<ztpan> T�Z); } <y:re> <u(iv> <div class="blankline"><u(iv> <li>Use a delegate:<vîi> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�4est() { <span class="d_keyword">void</span> <span class="d_keyword">delegate</span>() fp; <span class="d_keyword">void</span> foo() { fp(); } <span class="d_keyword">void</span> bar() { foo();�( fp = &bar; } </pre> </div> <div class="blankline"></div> �!�!zùl> <div class="blankline"></div> �!�!p>Nested functions cannot be overloaded.</p> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="function-pointers-delegates" href="#function-pointers-delegates">Function Pointers, Delegates and Closures<tæ><vv�(ŒÇ�) <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="function-pointers" href="#function-pointers">Function Pointers<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>A function�0ointer is declared�7ith the <span class="d_inlinecode donthyphenate notranslate">function<ztpan> keyword:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void</span> f(<span class="d_keyword">int<ztpan>); <span class="d_keyword">void<ztpan>�!�!span class="d_keyword">function<ztpan>(<span class="d_keyword">int</span>) fp = &f; <span class="d_comment">]å fp is a�0ointer�4o a function�4aking an int <ztpan></pre> </div> �!�!p>A function�0ointer can�0oint�4o a static nested function:<y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan>�!�!span class="d_keyword">function<ztpan>() fp; <span class="d_comment">]å fp is a�0ointer�4o a function returning an int </span> <span class="d_keyword">void</span> test() { �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> a = 7; �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> a + 0Ú0ü0¸�( fp =�.�.�.amp;foo; } <span class="d_keyword">void</span> main() { �!�!span class="d_keyword">assert<ztpan>(!fp); �4est(); �!�!span class="d_keyword">int</span> i = fp(); <span class="d_keyword">assert</span>(i == 10); } </pre> </div> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Two functions�7ith identical bodies, or�4wo functions �4hat compile to identical assembly code, are not guaranteed�4o have distinct function�0ointer�6alues. The implementation may merge functions bodies into one if�4hey compile to identical code.</div> <div class="blankline"></div> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int</span> abc(<span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">return</span> x + ±�( <span class="d_keyword">uint<ztpan> def(<span class="d_keyword">uint<ztpan>�9) { <span class="d_keyword">return</span> y + ±�( <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">function<ztpan>(<span class="d_keyword">int</span>) fp1 =�.�.�.amp;abc; <span class="d_keyword">uint<ztpan>�!�!span class="d_keyword">function<ztpan>(<span class="d_keyword">uint<ztpan>) fp�(N��)= &def; <span class="d_comment">]å Do not rely on fp1 and fp�(N��)being different values; the compiler may merge <ztpan><span class="d_comment">]å�4hem. <ztpan></pre> </div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="closures" href="#closures">Delegates & Closures</a></h3> <div class="blankline"><u(iv> <p>A�!�!a href="..ztpec/type.html#delegates">delegate<tæ> can be set�4o a non-static�!�!a href="#nested">nested function</a>:<y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan>�!�!span class="d_keyword">delegate<ztpan>() dg; <span class="d_keyword">void</span> test() { �!�!span class="d_keyword">int</span> a = 7; �!�!span class="d_keyword">int</span> foo() { <span class="d_keyword">return</span> a + 0Ú0ü0¸�( dg =�.�.�.amp;foo; �!�!span class="d_keyword">int</span> i = dg(); <span class="d_comment">]å i is set to 10 </span>} <span class="d_keyword">void</span> main() { �4est(); �!�!span class="d_keyword">int</span> i = dg(); <span class="d_comment">]å ok,�4est.a is in a closure and still exists <ztpan> <span class="d_keyword">assert</span>(i == 10); } </pre> </div> <div class="blankline"></div> �!�!p>The stack variables referenced by a nested function are still valid even after�4he function exits (NOTE this is different from D 1.0). This combining of�4he environment and�4he function is called a <i>dynamic closure</i>. </p> <div class="blankline"></div> �!�!p>Those referenced stack�6ariables�4hat make�5p the closure are allocated on�4he�?�?C heap, unless:<y:> <ul><li>The closure is passed�4o a <a href="#scope-parameters"><span class="d_inlinecode donthyphenate notranslate">scope</span> parameter<tæ>.</li> <li>The closure is an initializer for a <a href="../spectættribute.html#scope"><span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�6ariable<tæ>.</li> <li>The closure is assigned to a�!�!span class="d_inlinecode donthyphenate notranslate">scope<ztpan>�6ariable. <vîi> <zùl> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate">@nogc: <span class="d_keyword">void</span> f(<span class="d_keyword">scope<ztpan>�!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>()); <span class="d_keyword">void</span> g(<span class="d_keyword">int<ztpan>�!�!span class="d_keyword">delegate<ztpan>()); <span class="d_keyword">void</span> main() { �!�!span class="d_keyword">int</span> i; �!�!span class="d_keyword">int</span> h() { <span class="d_keyword">return</span> i;�( h(); <span class="d_comment">]å OK </span> �!�!span class="d_keyword">scope</span> x = &h; <span class="d_comment">]å OK </span> �8(); <span class="d_comment">]å OK </span> �!�!span class="d_comment">/tæuto y = &h; ]å error, can't allocate closure in @nogc function <ztpan> f(&h);�!�!span class="d_comment">/XëOK <ztpan> <span class="d_comment">]åg(&h);� Xëerror </span> <span class="d_comment">]å delegate literals <ztpan> f(() => i);�!�!span class="d_comment">/XëOK <ztpan> <span class="d_keyword">scope<ztpan> d = () => i;�!�!span class="d_comment">/XëOK <ztpan> d = () => i + 1; <span class="d_comment">]å OK </span> f(d); �!�!span class="d_comment">/u’(() => i); ]å error, can't allocate closure in @nogc function <ztpan>} </pre> </div> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> Returning addresses of stack variables, however, is not a closure and is an error. </div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="method-delegates" href="#method-delegates">Method Delegates</a></h3> <div class="blankline"><u(iv> <p>Delegates�4o non-static nested functions contain two pieces of data: the pointer to�4he stack frame of the lexically enclosing function (called�4he�!�!i>context pointer<v}>) and�4he address of the function. This is analogous to struct/class non-static member function delegates consisting of a�!�!i>this</i>�0ointer and �4he address of the member function. Both forms of delegates are indistinguishable, and are the same�4ype. �!�!y:> <p>A delegate can be set�4o a particular object and method�5sing�!�!span class="d_inlinecode donthyphenate notranslate">&obj.method<ztpan>:<y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">struct</span> Foo { <span class="d_keyword">int<ztpan> a; <span class="d_keyword">int<ztpan> get()"�!�!span class="d_keyword">return<ztpan> a; } } <span class="d_keyword">int</span> add1(<span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg) { <span class="d_keyword">return</span> dg() + 1; } <span class="d_keyword">void<ztpan> main() { Foo f = {7}; �!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() dg =�.�.�.amp;f.get;�!�!span class="d_comment">/Xëbind�4o an instance of Foo and a method </span> �!�!span class="d_keyword">int</span> i = add1(dg); <span class="d_keyword">assert</span>(i == 8); <span class="d_keyword">int<ztpan>�8 = 27; �!�!span class="d_keyword">int</span> abc() { <span class="d_keyword">return</span> x;�( i = add1(&abc); <span class="d_keyword">assert</span>(i == 28); } </pre> </div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="function-delegate-init" href="#function-delegate-init">Initialization</a></h3> <div class="blankline"><u(iv> <p>Function pointers are�+ero-initialized by default. They can be initialized to�4he address of any function (including a function literal). �!�?nitialization with�4he address of a function�4hat requires a context�0ointer is not allowed in @safe functions. </p> <div class="blankline"></div> �!�!div class="spec-boxes undefined-behavior"><b>Undefined Behavior:</b> Calling a function pointer that�7as set�4o point to a function that requires a context pointer. �!�!u(iv> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan> sfunc(); <span class="d_keyword">int<ztpan> member(); �!�!span class="d_comment">/Xëhas hidden `this` reference parameter </span>} @safe <span class="d_keyword">void</span> sun() { <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">function<ztpan>() fp = &S.sfunc; fp(); <span class="d_comment">]å Ok </span> fp = &S.member;�!�!span class="d_comment">/Xëerror </span>} @system <span class="d_keyword">void</span> moon() { �!�!span class="d_keyword">int</span> <span class="d_keyword">function</span>() fp =�.�.�.amp;S.member; <span class="d_comment">]å Ok because @system </span> fp();�!�!span class="d_comment">/Xëundefined behavior <ztpan>} </pre> <div class="blankline"></div> �!�!p>Delegates are zero-initialized by default. They can be initialized by taking�4he address of a non-static member function, but a context pointer must be supplied. They can be initialized by�4aking the address of a non-static nested function or function literal, �7here�4he context�0ointer�7ill be set�4o point to�4he stack frame, closure, or <span class="d_inlinecode donthyphenate notranslate">null<ztpan>. </p> <div class="blankline"></div> �!�!p>Delegates cannot be initialized by�4aking the address of a global function, a static member function, or a static nested function. �!�!y:> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">struct</span> S { <span class="d_keyword">static</span> <span class="d_keyword">int<ztpan> sfunc(); <span class="d_keyword">int<ztpan> member() { <span class="d_keyword">return</span> ±�( } <span class="d_keyword">void</span> main() { S s; <span class="d_keyword">int<ztpan>�!�!span class="d_keyword">delegate<ztpan>() dg = &s.member;�!�!span class="d_comment">/XëOk, s supplies context�0ointer <ztpan> <span class="d_keyword">assert</span>(dg() == 1); �!�!span class="d_comment">/u(g = &S.sfunc; � Xëerror </span> �!�!span class="d_comment">/u(g = &S.member;� Xëerror </span> <span class="d_keyword">int<ztpan> moon() { <span class="d_keyword">return</span> �([f�)�( dg = &moon; �!�!span class="d_comment">/XëOk <ztpan> <span class="d_keyword">assert</span>(dg() == �(SA�); �!�!span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> mars()"�!�!span class="d_keyword">return<ztpan> 2 2; } <span class="d_comment">]ådg =�.�.�.amp;mars; ]å error <ztpan> dg = ()"�!�!span class="d_keyword">return<ztpan> 2 2 2; };�!�!span class="d_comment">/XëOk <ztpan> <span class="d_keyword">assert</span>(dg() == 4); } </pre> � </div> �!�!p>The last assignment uses a�!�!a href="..ztpec/expression.html#FunctionLiteral"><i>FunctionLiteral<v}><tæ>,�7hich �!�!a href="..ztpec/expression.html#lambda-type-inference">is inferred</a> as a delegate.<y:> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> Function�0ointers can be�0assed to functions�4aking a delegate argument by�0assing �4hem through the <a href="../phoboszttd_functional.html#.toDelegate"><span class="d_inlinecode donthyphenate notranslate">std.functional.toDelegate</span><tæ> template, which converts any callable to a delegate with a�!�!span class="d_inlinecode donthyphenate notranslate">null</span> context pointer. �!�!u(iv> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="anonymous" href="#anonymous">Anonymous Functions and Anonymous Delegates</a></h3> <div class="blankline"><u(iv> <p>See�!�!a href="..ztpec/expression.html#FunctionLiteral"><i>FunctionLiteral<v}><tæ>s. </p> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="main" href="#main"><span class="d_inlinecode donthyphenate notranslate">main()<ztpan> Function<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>For console programs, <span class="d_inlinecode donthyphenate notranslate">main()<ztpan> serves as�4he entry�0oint. It gets called after all�4he�!�!a href="..ztpec/module.html#staticorder">module initializers</a> are run, and after any <a href="../speczùnittest.html">unittests<tæ> are run. After it returns, all�4he module destructors are run. �!�!span class="d_inlinecode donthyphenate notranslate">main()</span> must be declared as follows: �!�!y:> <div class="blankline"><u(iv> <pre class="bnf notranslate"><a id="MainFunction"><span class="gname">MainFunction</span><tæ>: �!�!a href="#MainReturnDecl"><i>MainReturnDecl</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">main()</span> <a href="#FunctionBody"><i>FunctionBody<v}><tæ> <a href="#MainReturnDecl"><i>MainReturnDecl<v}><tæ> <span class="d_inlinecode donthyphenate notranslate">main(string[]</span> <a href="../specvîex.html#Identifier"><i>Identifier<v}><tæ><span class="d_inlinecode donthyphenate notranslate">)<ztpan>�!�!a href="#FunctionBody"><i>FunctionBody</i></a> <div class="blankline"></div> <a id="MainReturnDecl"><span class="gname">MainReturnDecl</span><tæ>: �!�!span class="d_inlinecode donthyphenate notranslate">void</span> <span class="d_inlinecode donthyphenate notranslate">int</span> <a href="../speczËype.html#noreturn"><i>noreturn</i></a> �!�!a href="#auto-functions"><span class="d_inlinecode donthyphenate notranslate">auto</span><tæ> </pre> <div class="blankline"></div> �!�!ul> �!�!li>If <span class="d_inlinecode donthyphenate notranslate">main<ztpan> returns�!�!span class="d_inlinecode donthyphenate notranslate">void</span>,�4he OS will receive a�+ero value on success.<vîi> �!�!li>If <span class="d_inlinecode donthyphenate notranslate">main<ztpan> returns�!�!span class="d_inlinecode donthyphenate notranslate">void</span> or�!�!span class="d_inlinecode donthyphenate notranslate">noreturn</span>,�4he OS will receive a non-zero value on abnormal termination, such as an uncaught exception.<vîi> �!�!li>If <span class="d_inlinecode donthyphenate notranslate">main<ztpan> is declared as <span class="d_inlinecode donthyphenate notranslate">auto<ztpan>, the inferred return type must be one of <span class="d_inlinecode donthyphenate notranslate">void<ztpan>, <span class="d_inlinecode donthyphenate notranslate">int</span> and <span class="d_inlinecode donthyphenate notranslate">noreturn<ztpan>.<vîi> �!�!zùl> <div class="blankline"></div> �!�!p>If�4he�!�!span class="d_inlinecode donthyphenate notranslate">string[]</span> parameter is declared,�4he�0arameter�7ill hold arguments�0assed to�4he�0rogram by the OS. The first argument is typically the executable name, followed by any command-line arguments.</p> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> The runtime can remove any arguments prefixed�!�!span class="d_inlinecode donthyphenate notranslate">--DRT-</span>.</div> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> The aforementioned return� �0arameter�4ypes may be annotated with�!�!span class="d_inlinecode donthyphenate notranslate">const<ztpan>, <span class="d_inlinecode donthyphenate notranslate">immutable</span>. They may also be replaced by <span class="d_inlinecode donthyphenate notranslate">enum<ztpan>'s�7ith matching base types.</div> <div class="blankline"></div> �!�!p>The main function must have D linkage.</p> <div class="blankline"></div> �!�!p>Attributes may be added as needed, e.g. <span class="d_inlinecode donthyphenate notranslate">@safe</span>,�!�!span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan>, <span class="d_inlinecode donthyphenate notranslate">nothrow</span>, etc.<y:> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="betterc-main" href="#betterc-main"><span class="d_inlinecode donthyphenate notranslate">extern(C) main()</span> Function</a></h3> <div class="blankline"><u(iv> <p>Programs may define an <span class="d_inlinecode donthyphenate notranslate">extern(C) main<ztpan> function as an alternative to�4he standard <a href="#main">entry point<tæ>. This form is required for �!�!a href="..ztpec/betterc.html"><b>BetterC</b></a>�0rograms.</p> <div class="blankline"></div> �!�!p>A C <span class="d_inlinecode donthyphenate notranslate">main<ztpan> function must be declared as follows:</p> <div class="blankline"></div> <pre class="bnf notranslate"><a id="CMainFunction"><span class="gname">CMainFunction<ztpan></a>: <span class="d_inlinecode donthyphenate notranslate">extern (C)<ztpan>�!�!a href="#MainReturnDecl"><i>MainReturnDecl</i></a>�!�!span class="d_inlinecode donthyphenate notranslate">main(<a href="#CmainParameters"><i>CmainParameters</i></a><sub>opt</sub>)<ztpan>�!�!a href="..ztpec/statement.html#BlockStatement"><i>BlockStatement</i></a> <div class="blankline"></div> <a id="CmainParameters"><span class="gname">CmainParameters</span><tæ>: �!�!span class="d_inlinecode donthyphenate notranslate">int<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a> �!�!span class="d_inlinecode donthyphenate notranslate">int<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a>, <span class="d_inlinecode donthyphenate notranslate">char**<ztpan>�!�!a href="..ztpec/lex.html#Identifier"><i>Identifier</i></a> <y:re> <div class="blankline"><u(iv> <p>When defined,�4he first�4wo�0arameters denote a C-style array (length +�0ointer) that holds�4he arguments�0assed to�4he�0rogram by the OS. The third parameter is a POSIX extension called <span class="d_inlinecode donthyphenate notranslate">environ</span> and holds information about the current environment variables.</p> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> The exemption for storage classes� �!�!span class="d_inlinecode donthyphenate notranslate">enum</span>'s defined for a D <span class="d_inlinecode donthyphenate notranslate">main<ztpan> function also applies�4o C <span class="d_inlinecode donthyphenate notranslate">main<ztpan> functions.<u(iv> <div class="blankline"><u(iv> <p>This function�4akes�4he�0lace of the C main function and is executed immediately without any setup or�4eardown associated�7ith a D <span class="d_inlinecode donthyphenate notranslate">main<ztpan> function. Programs reliant on module constructors, module destructors, or�5nittests need to manually perform (de)initialization �5sing�4he appropriate�!�!a href="..y:hobos/core_runtime.html#Runtime">runtime functions</a>.<y:> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> Other system-specific entry points may exist, such as <span class="d_inlinecode donthyphenate notranslate">WinMain</span> and <span class="d_inlinecode donthyphenate notranslate">DllMain</span> on 2 2 2 2indows systems. </div> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> Programs targeting platforms which require a different signature for <span class="d_inlinecode donthyphenate notranslate">main<ztpan> can�5se a function with�!�!a href="..ztpec/pragma.html#mangle">explicit mangling<tæ>: <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">pragma<ztpan>(mangle,�!�!span class="d_string">"main"</span>) <span class="d_keyword">int</span> myMain(<span class="d_keyword">int</span> a,�!�!span class="d_keyword">int</span> b,�!�!span class="d_keyword">int</span> c) { �!�!span class="d_keyword">return<ztpan> 0; } </pre> <div class="blankline"></div> �!�!u(iv> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="function-templates" href="#function-templates">Function Templates<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>Functions can have compile�4ime arguments in�4he form of a�4emplate. See�!�!a href="..ztpec/template.html#function-templates">function�4emplates</a>.<y:> <div class="blankline"><u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="interpretation" href="#interpretation">Compile Time Function Execution (CTFE)<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>In contexts where a compile time�6alue is required, functions can be�5sed to compute�4hose�6alues. This is called <i>Compile Time Function Execution</i>, or�!�!i>CTFE</i>.<y:> <div class="blankline"><u(iv> <p>These contexts are:</p> <div class="blankline"></div> �!�!ul> �!�!li>initialization of a static variable or a <a href="../specu0num.html#manifest_constants">manifest constant</a></li> <li>static initializers of struct/class members<vîi> �!�!li>dimension of a <a href="../spectærrays.html#static-arrays">static array</a></li> <li>argument for a�!�!a href="..ztpec/template.html#template_value_parameter"> template�6alue�0arameter</a></li> <li><a href="../spec|sersion.html#staticif"><span class="d_inlinecode donthyphenate notranslate">static if</span><tæ><vîi> �!�!li><a href="..ztpec/version.html#staticforeach"><span class="d_inlinecode donthyphenate notranslate">static foreach<ztpan></a></li> <li><a href="../spec|sersion.html#static-assert"><span class="d_inlinecode donthyphenate notranslate">static assert<ztpan></a></li> <li><a href="../speczttatement.html#mixin-statement"> �!�!span class="d_inlinecode donthyphenate notranslate">mixin<ztpan> statement</a></li> <li><a href="../specy:ragma.html"><span class="d_inlinecode donthyphenate notranslate">pragma<ztpan> argument<tæ><vîi> �!�!li><a href="..ztpec/traits.html"><span class="d_inlinecode donthyphenate notranslate">__traits</span> argument</a></li> </ul> <div class="blankline"><u(iv> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">enum</span> eval(<span class="d_keyword">alias</span> arg) = arg; <span class="d_keyword">int</span> square(<span class="d_keyword">int</span> i) { �!�!span class="d_keyword">return<ztpan> i * i; } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">import</span> std.stdio; <span class="d_keyword">static</span> j = square(3); <span class="d_comment">]å CTFE </span> �7riteln(j); �!�!span class="d_keyword">assert<ztpan>(square(4) == ­); �!�!span class="d_comment">/Xërun time <ztpan> <span class="d_keyword">static</span> <span class="d_keyword">assert</span>(square(3) == 9);�!�!span class="d_comment">/XëCTFE <ztpan> writeln(eval�Zsquare(5)));�!�!span class="d_comment">/XëCTFE <ztpan>} </pre> </div> <div class="blankline"></div> �!�!p>The function must have a�!�!a href="#FunctionBody"><i>FunctionBody</i></a>.<y:> <div class="blankline"><u(iv> <p>CTFE is subject�4o the following restrictions:<y:> <div class="blankline"><u(iv> <ol> <li>Expressions may not reference any mutable static�6ariables.<vîi> <div class="blankline"></div> �!�!li><a href="..ztpec/iasm.html#asmstatements">AsmStatements</a> are not�0ermitted</li> <div class="blankline"><u(iv> <li>Non-portable casts (e.g., from�!�!span class="d_inlinecode donthyphenate notranslate">int[]<ztpan>�4o <span class="d_inlinecode donthyphenate notranslate">float[]</span>), including casts which depend on endianness, are not permitted. Casts between signed and unsigned�4ypes are�0ermitted.<vîi> <div class="blankline"></div> �!�!li>Reinterpretation of overlapped fields in a union is not�0ermitted.<vîi> <div class="blankline"></div> �!�!li>Undefined behavior must not occur.<vîi> �!�!wól> <div class="blankline"></div> �!�!p>Pointers are�0ermitted in CTFE, provided�4hey are used safely:</p> <div class="blankline"></div> �!�!ul> �!�!li> Pointer arithmetic is�0ermitted only on�0ointers which point to static or dynamic array elements. A�0ointer may also point to�4he first element�0ast the array, although such�0ointers cannot be dereferenced. Pointer arithmetic on pointers�7hich are null, or which point to a non-array, is not allowed. </li> <div class="blankline"><u(iv> <li> Ordered comparison (<span class="d_inlinecode donthyphenate notranslate"><<ztpan>, <span class="d_inlinecode donthyphenate notranslate"><<ztpan><span class="d_inlinecode donthyphenate notranslate">=</span>,�!�!span class="d_inlinecode donthyphenate notranslate">></span>,�!�!span class="d_inlinecode donthyphenate notranslate">>=<ztpan>) between two pointers is permitted when both pointers�0oint�4o the same array, or�7hen at least one �0ointer is <span class="d_inlinecode donthyphenate notranslate">null<ztpan>. </li> <div class="blankline"><u(iv> <li> Pointer comparisons between discontiguous memory blocks are illegal, �5nless two such comparisons are combined using <span class="d_inlinecode donthyphenate notranslate">&&<ztpan> or <span class="d_inlinecode donthyphenate notranslate">|</span><span class="d_inlinecode donthyphenate notranslate">|<ztpan>�4o yield a result�7hich is independent of�4he ordering of memory blocks. Each comparison must consist of two pointer expressions compared�7ith <span class="d_inlinecode donthyphenate notranslate"><<ztpan>, <span class="d_inlinecode donthyphenate notranslate"><<ztpan><span class="d_inlinecode donthyphenate notranslate">=</span>,�!�!span class="d_inlinecode donthyphenate notranslate">></span>, or <span class="d_inlinecode donthyphenate notranslate">><ztpan><span class="d_inlinecode donthyphenate notranslate">=</span>, and may optionally be negated�7ith <span class="d_inlinecode donthyphenate notranslate">!</span>. For example, the expression�!�!span class="d_inlinecode donthyphenate notranslate">(p1 >�i1 &&�0�(N��)<= q2)<ztpan> is permitted when�!�!span class="d_inlinecode donthyphenate notranslate">p1</span>,�!�!span class="d_inlinecode donthyphenate notranslate">p2</span> are expressions yielding�0ointers to memory block <i>P</i>, and <span class="d_inlinecode donthyphenate notranslate">q²ztpan>, <span class="d_inlinecode donthyphenate notranslate">q�(vã�)ztpan> are expressions�9ielding pointers�4o memory block�!�!i>Q<v}>, even when�!�!i>P<v}> and <i>Q</i> are �5nrelated memory blocks. It returns�4rue if�!�!span class="d_inlinecode donthyphenate notranslate">[p1..p�3�3</span> lies inside <span class="d_inlinecode donthyphenate notranslate">[q1..q2]<ztpan>, and false otherwise. Similarly, the expression�!�!span class="d_inlinecode donthyphenate notranslate">(p1 <�i1 ||�0�(N��)>�i�(SA�)</span> is�4rue if �!�!span class="d_inlinecode donthyphenate notranslate">[p1..p�3�3</span> lies outside�!�!span class="d_inlinecode donthyphenate notranslate">[q1..q�3�3</span>, and false otherwise. </li> <div class="blankline"><u(iv> <li> Equality comparisons (<span class="d_inlinecode donthyphenate notranslate">==<ztpan>, <span class="d_inlinecode donthyphenate notranslate">!=<ztpan>, <span class="d_inlinecode donthyphenate notranslate">is<ztpan>, <span class="d_inlinecode donthyphenate notranslate">!is</span>) are �0ermitted between all�0ointers,�7ithout restriction. </li> <div class="blankline"><u(iv> <li> Any pointer may be cast to�!�!span class="d_inlinecode donthyphenate notranslate">void*<ztpan> and from <span class="d_inlinecode donthyphenate notranslate">void*</span> back�4o its original�4ype. Casting between�0ointer and non-pointer�4ypes is illegal. �!�!vîi> �!�!zùl> <div class="blankline"></div> �!�!p>The above restrictions apply only to expressions�7hich are actually evaluated. For example: </p> <pre class="d_code notranslate"><span class="d_keyword">static<ztpan>�!�!span class="d_keyword">int</span> y = 0; <span class="d_keyword">int<ztpan> countTen(<span class="d_keyword">int<ztpan>�8) { <span class="d_keyword">if</span> (x�.�.�.gt; 10) ++y; <span class="d_comment">]å access static�6ariable </span> �!�!span class="d_keyword">return<ztpan>�8; } <span class="d_keyword">static<ztpan>�!�!span class="d_keyword">assert<ztpan>(countTen(6) == 6); �!�!span class="d_comment">/XëOK <ztpan><span class="d_keyword">static</span> <span class="d_keyword">assert</span>(countTen(1�(SA�) == ); <span class="d_comment">]å invalid, modifies�9. </span><y:re> <p>The�!�!span class="d_inlinecode donthyphenate notranslate">__ctfe</span> boolean pseudo-variable evaluates to�!�!span class="d_keyword">true<ztpan> during CTFE but�!�!span class="d_keyword">false</span> otherwise. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> <span class="d_inlinecode donthyphenate notranslate">__ctfe<ztpan> can be used�4o provide an alternative execution�0ath to avoid operations which are forbidden in CTFE. Every�5sage of <span class="d_inlinecode donthyphenate notranslate">__ctfe<ztpan> is statically evaluated and has no run-time cost. �!�!u(iv> <div class="blankline"><u(iv> <p>Non-recoverable errors (such as�!�!span class="d_keyword">assert<ztpan> failures) are illegal. </p> <div class="blankline"></div> �!�!div class="spec-boxes implementation-defined"><b>Implementation Defined:</b> Executing functions�6ia CTFE can take considerably longer�4han executing it at run time. If�4he function goes into an infinite loop, it may cause�4he compiler to hang. �!�!u(iv> <div class="blankline"><u(iv> <div class="spec-boxes implementation-defined"><b>Implementation Defined:<u> Functions executed�6ia CTFE can give different results from run time�7hen implementation-defined behavior occurs. </div> <div class="blankline"></div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="string-mixins" href="#string-mixins">String Mixins and Compile Time Function Execution<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>All functions that execute in CTFE must also be executable at run time. The compile time evaluation of a function does�4he equivalent of running�4he function at run�4ime. The semantics of a function cannot depend on compile time�6alues of�4he function. For example:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan> foo(string s) { �!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">mixin</span>(s); } <span class="d_keyword">const</span> <span class="d_keyword">int<ztpan>�8 = foo(<span class="d_string">"1"<ztpan>); <y:re> <div class="blankline"><u(iv> <div class="blankline"></div> is illegal, because�4he runtime code for <span class="d_inlinecode donthyphenate notranslate">foo</span> cannot be generated. <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> A function�4emplate,�7here�!�!span class="d_inlinecode donthyphenate notranslate">s<ztpan> is a template argument, �7ould be the appropriate method�4o implement this sort of�4hing. </div> <div class="blankline"></div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="nogc-functions" href="#nogc-functions">No-GC Functions<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>No-GC functions are functions marked�7ith the <span class="d_inlinecode donthyphenate notranslate">@nogc</span> attribute. Those functions do not allocate memory on�4he�?�?C heap. These operations are not allowed in No-GC functions: �!�!y:> <div class="blankline"><u(iv> <ol> <li><a href="../specu0xpression.html#array-literal-heap">constructing an array</a> on the heap</li> <li>resizing an array by�7riting�4o its <span class="d_inlinecode donthyphenate notranslate">.length</span> property</li> <li><a href="../specu0xpression.html#CatExpression">array concatenation<tæ><vîi> �!�!li><a href="..ztpec/expression.html#simple_assignment_expressions">array appending</a></li> <li><a href="../specu0xpression.html#AssocArrayLiteral">constructing an associative array<tæ><vîi> �!�!li><a href="..ztpec/expression.html#IndexOperation">indexing</a> an associative array <div class="spec-boxes rationale"><b>Rationale:<u> Indexing may�4hrow a�!�!span class="d_inlinecode donthyphenate notranslate">RangeError</span> if�4he specified key is not present.</div> </li> <li><a href="../specu0xpression.html#NewExpression">allocating an object�7ith <span class="d_inlinecode donthyphenate notranslate">new</span><tæ> on�4he heap <div class="spec-boxes note"><b>Note:<u> <span class="d_inlinecode donthyphenate notranslate">new</span> declarations of <span class="d_inlinecode donthyphenate notranslate">class</span> types in function scopes are compatible with �!�!span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan> if used�4o initialize a�!�!a href="..ztpec/attribute.html#scope-class-var"><span class="d_inlinecode donthyphenate notranslate">scope</span> variable</a>, as�4hey result in allocations on�4he stack.<u(iv><vîi> �!�!li>calling functions�4hat are not <span class="d_inlinecode donthyphenate notranslate">@nogc</span>,�5nless the call is in a�!�!a href="..ztpec/version.html#ConditionalStatement"><i>ConditionalStatement</i></a> controlled by a�!�!a href="..ztpec/version.html#DebugCondition"><i>DebugCondition</i></a></li> </ol> <div class="blankline"><u(iv> <pre class="d_code notranslate">@nogc <span class="d_keyword">void</span> foo() { <span class="d_keyword">auto</span> a = ['a']; <span class="d_comment">]å (1) error, allocates </span> a.length = ± <span class="d_comment">]å (�(SA�) error, array resizing allocates <ztpan> a = a ~ a; �!�!span class="d_comment">/Xë(3) error, arrays concatenation allocates </span> a�)= 'c'; <span class="d_comment">]å (4) error, appending to arrays allocates </span> <span class="d_keyword">auto</span> aa = [<span class="d_string">"x"</span>:o; <span class="d_comment">]å (5) error, allocates </span> aa[<span class="d_string">"abc"</span>]; <span class="d_comment">]å (6) error, indexing may allocate and throws <ztpan> �!�!span class="d_keyword">auto<ztpan>�0 =�!�!span class="d_keyword">new</span> <span class="d_keyword">int<ztpan>; �!�!span class="d_comment">/Xë(7) error, operator new allocates </span> �!�!span class="d_keyword">scope</span> <span class="d_keyword">auto</span> p = <span class="d_keyword">new<ztpan>�?�?enericClass();�!�!span class="d_comment">/Xë(7) Ok <ztpan> bar(); �!�!span class="d_comment">/Xë(8) error, bar() may allocate </span> �!�!span class="d_keyword">debug</span> bar(); �!�!span class="d_comment">/Xë(8) Ok <ztpan>} <span class="d_keyword">void</span> bar() { } </pre> <div class="blankline"></div> �!�!p>No-GC functions can only�5se a closure if it is <span class="d_inlinecode donthyphenate notranslate">scope</span> - see <a href="#closures">Delegates & Closures</a>. </p> <div class="blankline"></div> <pre class="d_code notranslate">@nogc�!�!span class="d_keyword">int</span> <span class="d_keyword">delegate</span>() foo() { <span class="d_keyword">int<ztpan> n; �!�!span class="d_comment">/Xëerror,�6ariable n cannot be allocated on heap </span> �!�!span class="d_keyword">return<ztpan> (){�!�!span class="d_keyword">return<ztpan> n; } <span class="d_comment">]å since `n` escapes `foo()`, a closure is required </span>} <y:re> <div class="blankline"><u(iv> <p><span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan> affects�4he�4ype of�4he function. A�!�!span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan> function is covariant�7ith a non-<span class="d_inlinecode donthyphenate notranslate">@nogc</span> function. </p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">void<ztpan>�!�!span class="d_keyword">function<ztpan>() fp; <span class="d_keyword">void<ztpan>�!�!span class="d_keyword">function<ztpan>() @nogc gp; <span class="d_comment">]å�0ointer�4o @nogc function <ztpan> <span class="d_keyword">void<ztpan> foo(); @nogc <span class="d_keyword">void</span> bar(); <span class="d_keyword">void</span> test() { fp = &foo; <span class="d_comment">]å ok </span> fp = &bar; <span class="d_comment">]å ok, it's covariant </span> gp = &foo; <span class="d_comment">]å error, not contravariant </span> gp = &bar; <span class="d_comment">]å ok </span>} <y:re> <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b> Since a function marked�!�!span class="d_inlinecode donthyphenate notranslate">@nogc<ztpan>�7ill not do any�?�?C allocations, �4hat implies it�7ill not cause any GC collections�4o run.�?�!owever, another thread may still allocate with�4he�?�?C and trigger a collection. The recommended way to�0revent�?�?C collections from being run is to call <a href="https:/u(lang.orgy:hobos/core_memory.html#GC.disable">core.memory.GC.disable()<tæ> instead. This will stop collections from being run in any thread�5ntil a corresponding call to�!�!span class="d_inlinecode donthyphenate notranslate">core.memory.GC.enable()<ztpan> is run.�?�?C allocations can still be�0erformed �7hen <span class="d_inlinecode donthyphenate notranslate">GC.disable()<ztpan> is in effect.</div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="function-safety" href="#function-safety">Function Safety<tæ><vv�(ŒÇ�) <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="safe-functions" href="#safe-functions">Safe Functions</a></h3> <div class="blankline"><u(iv> <p>Safe functions are marked�7ith the <span class="d_inlinecode donthyphenate notranslate">@safe</span> attribute. �!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> can be inferred, see <a href="#function-attribute-inference">Function Attribute�!�?nference</a>.<y:> <div class="blankline"><u(iv> <p>Safe functions have�!�!a href="#safe-interfaces">safe interfaces<tæ>. An implementation must enforce this by restricting the function's body to operations that are known�4o be safe, except for calls to�!�!a href="#trusted-functions"><span class="d_inlinecode donthyphenate notranslate">@trusted<ztpan> functions</a>.<y:> <div class="blankline"><u(iv> <p>The following restrictions are enforced by the compiler in safe functions:<y:> <div class="blankline"><u(iv> <ul> <li>No casting from a pointer type�!�!span class="d_inlinecode donthyphenate notranslate">T<ztpan>�4o any type�!�!span class="d_inlinecode donthyphenate notranslate">U<ztpan>�7ith pointers, except�7hen:</li> <ul><li><span class="d_inlinecode donthyphenate notranslate">T</span> implicitly converts to�!�!span class="d_inlinecode donthyphenate notranslate">U<ztpan></li> <li><span class="d_inlinecode donthyphenate notranslate">U</span> <a href="../specu0xpression.html#cast_class">implements<tæ> class or interface �!�!span class="d_inlinecode donthyphenate notranslate">T<ztpan>, and both�4ypes are�!�!span class="d_inlinecode donthyphenate notranslate">extern(D)<ztpan></li> <li><span class="d_inlinecode donthyphenate notranslate">T.opCast!U<ztpan> is <span class="d_inlinecode donthyphenate notranslate">@safe</span><vîi> <li>Both types <a href="../specu0xpression.html#cast_array">are dynamic arrays<tæ>, or both�4ypes�!�!a href="..ztpec/expression.html#cast_pointers">are raw�0ointers<tæ>, and: <ul><li>The target element�4ype is not a�0ointer�4ype<vîi> <li>The�4arget element type is not mutable when�4he source element type is a pointer type</li> <li>Either�4he�4arget element type is a dynamic array, or the target element �4ype is no larger�4han the source element�4ype<vîi> <li>Any source element type modifiers implicitly convert to�4he�4arget element type modifiers</li> <li>Neither element type is a function�4ype<vîi> <li>The�4arget element type is not mutable when�4he source type is <span class="d_inlinecode donthyphenate notranslate">void[]<ztpan></li> <li>The target element�4ype only stores <a href="#safe-values">safe values</a></li> <li>The source element�4ype only stores safe�6alues when�4he�4arget element type is mutable<vîi> <li>Neither element�4ype is�!�!a href="..ztpec/struct.html#opaque_struct_unions">opaque</a>.<vîi> <zùl></li> </ul> <li>No casting from any non-pointer type�4o a pointer type.<vîi> �!�!li>No <a href="../specu0xpression.html#pointer_arithmetic">pointer arithmetic<tæ> (including�0ointer indexing & slicing).<vîi> �!�!li>Cannot access array�!�!a href="..ztpec/arrays.html#ptr-property"><span class="d_inlinecode donthyphenate notranslate">.ptr<ztpan>�0roperty<tæ>.</li> <li>Cannot copy into a�!�!a href="..ztpec/arrays.html#void_arrays">void array<tæ>.</li> <li>Cannot access union fields�4hat:</li> <ul><li>Have�0ointers or references overlapping with other�4ypes</li> <li>Have invariants overlapping with other�4ypes</li> <li>Overlap with fields that could become <a href="#safe-values">unsafe values</a></li> </ul> <li>Calling any <a href="#system-functions">System Functions</a>.<vîi> �!�!li>No catching of exceptions�4hat are not derived from �!�!a href="https:]ådlang.org/phoboswóbject.html#.Exception"><span class="d_inlinecode donthyphenate notranslate">class Exception<ztpan></a>.<vîi> �!�!li><a href="..ztpec/iasm.html#asmstatements">Inline assembler<tæ> must be marked as <span class="d_inlinecode donthyphenate notranslate">@trusted<ztpan>.<vîi> �!�!li>No explicit casting (except�7ith a matching�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan>�!�!span class="d_inlinecode donthyphenate notranslate">opCast</span>) of:</li> <ul><li>mutable objects to immutable (except basic data types)</li> <li>immutable objects to mutable (except basic data types)</li> <li>thread local objects�4o shared</li> <li>shared objects�4o thread local</li> </ul> <li>Cannot access <a href="../spectættribute.html#system-variables"><span class="d_inlinecode donthyphenate notranslate">@system</span><tæ> or�!�!span class="d_inlinecode donthyphenate notranslate">__gshared<ztpan>�6ariables.<vîi> �!�!li>Cannot use <span class="d_inlinecode donthyphenate notranslate">void<ztpan> initializers for types containing:<vîi> <ul><li>Pointers/reference types<vîi> <li>Types�7ith invariants</li> <li>Unsafe�6alues<vîi> <zùl> �!�!zùl> <div class="blankline"></div> �!�!div class="spec-boxes note"><b>Note:</b> 2 2 2 2hen indexing or slicing an array, an out of bounds access will cause a runtime error. </div> <div class="blankline"></div> �!�!p>Functions nested inside safe functions default�4o being safe functions. </p> <div class="blankline"></div> �!�!p>Safe functions are covariant�7ith trusted or system functions.</p> <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> Mark as many functions�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> as practical.</div> <div class="blankline"></div> <h4>Safe External Functions</h4> <div class="blankline"><u(iv> <p>External functions don't have a function body�6isible�4o the compiler: </p> <pre class="d_code notranslate">@safe�!�!span class="d_keyword">extern<ztpan> (C)�!�!span class="d_keyword">void<ztpan>�0lay(); <y:re> and so safety cannot be verified automatically. <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b> Explicitly set an attribute for external functions rather �4han relying on default settings.</div> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="trusted-functions" href="#trusted-functions">Trusted Functions<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>Trusted functions are marked�7ith the <span class="d_inlinecode donthyphenate notranslate">@trusted<ztpan> attribute.<y:> <div class="blankline"><u(iv> <p>Like <a href="#safe-functions">safe functions</a>, trusted functions have�!�!a href="#safe-interfaces">safe interfaces<tæ>. Unlike safe functions, this is not enforced by restrictions on the function body.�!�?nstead, it is the responsibility of the programmer�4o ensure�4hat the interface of a�4rusted function is safe.</p> <div class="blankline"></div> �!�!p>Example:</p> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">immutable</span>(<span class="d_keyword">int<ztpan>)* f(<span class="d_keyword">int</span>*�0) @trusted { �!�!span class="d_keyword">version</span> (none)�0[2] = ª; <span class="d_comment">]å�!�?nvalid. p[�3�3 is out of bounds. This line�7ould exhibit�5ndefined <ztpan> <span class="d_comment">]å behavior. <ztpan> �!�!span class="d_keyword">version</span> (none)�0[1] = ª; <span class="d_comment">]å�!�?nvalid. In�4his program,�0[1] happens to be in-bounds, so the </span> �!�!span class="d_comment">/Xëline�7ould not exhibit�5ndefined behavior, but a�4rusted function </span> �!�!span class="d_comment">/Xëis not allowed�4o rely on this. </span> <span class="d_keyword">version<ztpan> (none) <span class="d_keyword">return</span> <span class="d_keyword">cast</span>(<span class="d_keyword">immutable<ztpan>) p; �!�!span class="d_comment">/XëInvalid. @safe code still has mutable access and could�4rigger <ztpan> <span class="d_comment">]å�5ndefined behavior by overwriting�4he�6alue later on. <ztpan> �!�!span class="d_keyword">int</span>*�0�(N��)= <span class="d_keyword">new<ztpan>�!�!span class="d_keyword">int</span>; *p2 = 2 2 2�([f�) �!�!span class="d_keyword">return<ztpan>�!�!span class="d_keyword">cast<ztpan>(<span class="d_keyword">immutable</span>)�0�([f�) �!�!span class="d_comment">/XëValid. After f returns, no mutable aliases of p2 can exist. </span>} <span class="d_keyword">void</span> main() @safe { �!�!span class="d_keyword">int</span>[�3�3 a = [10, �(eå�)]; �!�!span class="d_keyword">int</span>* mp = &a[0]; �!�!span class="d_keyword">immutable</span>(<span class="d_keyword">int<ztpan>)* ip = f(mp); �!�!span class="d_keyword">assert<ztpan>(a[1] == 20); <span class="d_comment">]å�?�?uaranteed. f cannot access a[1]. <ztpan> <span class="d_keyword">assert</span>(ip !<span class="d_keyword">is</span> mp);�!�!span class="d_comment">/XëGuaranteed. f cannot introduce�5nsafe aliasing. </span>} <y:re> <div class="blankline"><u(iv> <p>Trusted functions may call safe, trusted, or system functions. </p> <div class="blankline"></div> �!�!p>Trusted functions are covariant with safe or system functions.</p> <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> Trusted functions should be kept small so that�4hey are easier�4o manually�6erify. �!�!u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="system-functions" href="#system-functions">System Functions<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>System functions are functions not marked with�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> or <span class="d_inlinecode donthyphenate notranslate">@trusted<ztpan> and are not nested inside�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> functions. System functions may be marked�7ith the <span class="d_inlinecode donthyphenate notranslate">@system</span> attribute. A function being system does not mean it actually is unsafe, it just means that its safety must be manually�6erified. �!�!y:> <div class="blankline"><u(iv> <p>System functions are <b>not</b> covariant�7ith trusted or safe functions. �!�!y:> <div class="blankline"><u(iv> <p>System functions can call safe and trusted functions.</p> <div class="blankline"></div> �!�!div class="spec-boxes best-practice"><b>Best Practices:<u> When in doubt, mark <span class="d_inlinecode donthyphenate notranslate">extern (C)<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">extern (C++)</span> functions as �!�!span class="d_inlinecode donthyphenate notranslate">@system<ztpan>�7hen their implementations are not in D, as�4he D compiler will be unable�4o check them. Most of them are�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan>, but will need to be manually checked.<u(iv> <div class="blankline"><u(iv> <div class="spec-boxes best-practice"><b>Best Practices:</b> The number and size of system functions should be minimized. This minimizes�4he�7ork necessary to manually check for safety.<u(iv> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="safe-interfaces" href="#safe-interfaces">Safe Interfaces</a></h3> <div class="blankline"><u(iv> <p>When a function call's arguments,�!�!a href="#closures">any context</a> and accessible globals each have <a href="#safe-values">safe values</a>�7ith <a href="#safe-aliasing">safe aliasing</a>, that function has a safe interface�7hen:</p> �!�!ol> �!�!li>it cannot exhibit �!�!a href="..ztpec/glossary.html#undefined_behavior">undefined behavior</a>, and<vîi> �!�!li>it cannot create unsafe�6alues that are accessible from �!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> code (e.g.,�6ia return values, global�6ariables, or�!�!span class="d_inlinecode donthyphenate notranslate">ref<ztpan>�0arameters), and<vîi> �!�!li>it cannot introduce�5nsafe aliasing�4hat is accessible from �!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> code.</li> </ol> <div class="blankline"><u(iv> <p>Functions�4hat meet�4hese requirements may be �!�!a href="#safe-functions"><span class="d_inlinecode donthyphenate notranslate">@safe<ztpan></a> or <a href="#trusted-functions"><span class="d_inlinecode donthyphenate notranslate">@trusted</span><tæ>. Function that do not meet�4hese requirements can only be <a href="#system-functions"><span class="d_inlinecode donthyphenate notranslate">@system</span><tæ>.</p> <div class="blankline"></div> �!�!p>Examples:<y:> <div class="blankline"><u(iv> <ul> <li> C's <span class="d_inlinecode donthyphenate notranslate">free<ztpan> does not have a safe interface: <pre class="d_code notranslate"><span class="d_keyword">extern<ztpan> (C) @system�!�!span class="d_keyword">void<ztpan> free(<span class="d_keyword">void</span>*�0tr); <y:re> because <span class="d_inlinecode donthyphenate notranslate">free(p)</span> invalidates <span class="d_inlinecode donthyphenate notranslate">p</span>, making its value unsafe. <span class="d_inlinecode donthyphenate notranslate">free<ztpan> can only be�!�!span class="d_inlinecode donthyphenate notranslate">@system<ztpan>. </li> <li> C's <span class="d_inlinecode donthyphenate notranslate">strlen<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">memcpy</span> do not have safe interfaces: <pre class="d_code notranslate"><span class="d_keyword">extern<ztpan> (C) @system size_t strlen(<span class="d_keyword">char<ztpan>* s); <span class="d_keyword">extern</span> (C) @system <span class="d_keyword">void</span>* memcpy(<span class="d_keyword">void</span>* dst, <span class="d_keyword">void</span>* src, size_t nbytes); </pre> because�4hey iterate pointers based on unverified assumptions (<span class="d_inlinecode donthyphenate notranslate">strlen<ztpan> assumes�4hat <span class="d_inlinecode donthyphenate notranslate">s</span> is�+ero-terminated; <span class="d_inlinecode donthyphenate notranslate">memcpy<ztpan> assumes �4hat the memory objects�0ointed�4o by�!�!span class="d_inlinecode donthyphenate notranslate">dst<ztpan> and�!�!span class="d_inlinecode donthyphenate notranslate">src<ztpan> are at least <span class="d_inlinecode donthyphenate notranslate">nbytes<ztpan> big). Any function that�4raverses a C string passed as an argument can only be <span class="d_inlinecode donthyphenate notranslate">@system</span>. Any function that�4rusts a separate�0arameter for array bounds can only be <span class="d_inlinecode donthyphenate notranslate">@system</span>. �!�!vîi> �!�!li> C's�!�!span class="d_inlinecode donthyphenate notranslate">malloc</span> does have a safe interface: <pre class="d_code notranslate"><span class="d_keyword">extern</span> (C) @trusted�!�!span class="d_keyword">void<ztpan>* malloc(size_t sz); <y:re> It does not exhibit undefined behavior for any input. It returns either a valid pointer,�7hich is safe, or�!�!span class="d_inlinecode donthyphenate notranslate">null</span> which is also safe. It returns a�0ointer�4o a fresh allocation, so it cannot introduce any�5nsafe aliasing. <div class="spec-boxes note"><b>Note:<u> The implementation of <span class="d_inlinecode donthyphenate notranslate">malloc<ztpan> is most likely @system code.<u(iv> </li> <li> A D version of�!�!span class="d_inlinecode donthyphenate notranslate">memcpy</span> can have a safe interface: �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate">@safe�!�!span class="d_keyword">void<ztpan> memcpy(E)(E[] src, E[] dst) { �!�!span class="d_keyword">import<ztpan> std.math : min; �!�!span class="d_keyword">foreach</span> (i; 0 .. min(src.length, dst.length)) { dst[i] = src[i]; �( } <y:re> <u(iv> because the rules for <a href="#safe-values">safe values</a> ensure that�4he lengths of the arrays are correct. </li> </ul> <div class="blankline"><u(iv> <h0Ü0ë0È<a class="anchor" title="Permalink�4o this section" id="safe-values" href="#safe-values">Safe Values</a></h3> <div class="blankline"><u(iv> <p>A�6ariable or field�!�!a href="..ztpec/attribute.html#system-variables"> marked as�!�!span class="d_inlinecode donthyphenate notranslate">@system<ztpan></a> does not hold a safe value, regardless of its�4ype.</p> <div class="blankline"></div> �!�!p>For a <a href="../speczËype.html#bool"><span class="d_inlinecode donthyphenate notranslate">bool</span><tæ>, only 0 and 1 are safe�6alues.</p> <div class="blankline"></div> �!�!p>For all other <a href="../speczËype.html#basic-data-types">basic data types<tæ>, all �0ossible bit patterns are safe.</p> <div class="blankline"></div> �!�!p>A pointer is a safe value when it is one of:</p> �!�!ol> �!�!li><span class="d_inlinecode donthyphenate notranslate">null</span> - <a href="#null-dereferences">see below</a></li> <li>it�0oints to a memory object�4hat is live and the pointed to�6alue in that memory object is safe.<vîi> �!�!wól> �!�!p>Examples:<y:> <div class="runnable-examples"> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan>* n = <span class="d_keyword">null</span>;�!�!span class="d_comment">/* n is safe because dereferencing null must either crash or abort. *_Ãztpan> <span class="d_keyword">int</span>*�8 =�!�!span class="d_keyword">cast<ztpan>(<span class="d_keyword">int</span>*) 0xDEADBEEF; <span class="d_comment">\"�8 is (most likely) unsafe because it is not a�6alid�0ointer and cannot be dereferenced. *_Ãztpan> <span class="d_keyword">import</span> core.stdc.stdlib: malloc, free; <span class="d_keyword">int<ztpan>* p1 =�!�!span class="d_keyword">cast<ztpan>(<span class="d_keyword">int</span>*) malloc(<span class="d_keyword">int</span>.sizeof);�!�!span class="d_comment">/* p1 is safe because�4he �0ointer is valid and *p1 is safe regardless of its actual�6alue. */</span> free(p1); <span class="d_comment">\" This makes p1�5nsafe. *_Ãztpan> <span class="d_keyword">int</span>** p2 =�.�.�.amp;p1; <span class="d_comment">\" 2 2 2 2hile it can be dereferenced,�0�(N��)is�5nsafe because p1 is unsafe. */</span> p1 =�!�!span class="d_keyword">null<ztpan>; <span class="d_comment">\" This makes p1 and�0�(N��)safe. */</span> </pre> � </div> <div class="blankline"></div> �!�!p>A dynamic array is safe when:<y:> <ol> <li>its pointer is safe, and</li> <li>its length is in-bounds with�4he corresponding memory object, and<vîi> �!�!li>all its elements are safe.<vîi> �!�!wól> <div class="blankline"></div> �!�!p>Examples:<y:> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">int<ztpan>[] f() @system { �!�!span class="d_keyword">bool<ztpan> b =�!�!span class="d_keyword">true<ztpan>; <span class="d_comment">\" b is initialized safe *_Ãztpan> *(<span class="d_keyword">cast<ztpan>(<span class="d_keyword">ubyte</span>*) &b) = 0xAA; <span class="d_comment">\" b is now unsafe because it's not 0 or 1 *_Ãztpan> �!�!span class="d_keyword">int</span>[�5p¹ a; <span class="d_keyword">int<ztpan>[] d1 = a[0 .. 2 2];�!�!span class="d_comment">/* d1 is safe. */</span> <span class="d_keyword">int<ztpan>[] d�(N��)= a.ptr[0 .. 2 2 2];�!�!span class="d_comment">/* d2 is unsafe because it goes beyond a's bounds. */</span> <span class="d_keyword">int<ztpan>*[] d3 = [<span class="d_keyword">cast</span>(<span class="d_keyword">int<ztpan>*) 0xDEADBEEF]; <span class="d_comment">\" d0µ0ó0Á0ü0àis�5nsafe because the element is�5nsafe. *_Ãztpan> �!�!span class="d_keyword">return<ztpan> d±�!�!span class="d_comment">/* Up�4o here, d1�7as safe, but its�0ointer becomes invalid�7hen the function returns, so�4he returned dynamic array is�5nsafe. *_Ãztpan> } <y:re> <u(iv> <div class="blankline"><u(iv> <p>A static array is safe when all its elements are safe. Regardless of the element type, a static array�7ith length�+ero is always safe.<y:> <div class="blankline"><u(iv> <p>An associative array is safe when all its keys and elements are safe.</p> <div class="blankline"></div> �!�!p>A structzùnion instance is safe when:<y:> <ol> <li>the values of its accessible fields are safe, and<vîi> �!�!li>it does not introduce�!�!a href="#safe-aliasing">unsafe aliasing<tæ> with�5nions.</li> </ol> <div class="blankline"><u(iv> <p>Examples:</p> �!�!div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"> <span class="d_keyword">void</span> fun() { <span class="d_keyword">struct</span> S { <span class="d_keyword">int<ztpan>* p;�( S s1 = S(<span class="d_keyword">new<ztpan>�!�!span class="d_keyword">int</span>); <span class="d_comment">\" s1 is safe. *_Ãztpan> S s�(N��)= S(<span class="d_keyword">cast</span>(<span class="d_keyword">int<ztpan>*) 0xDEADBEEF); <span class="d_comment">\" s�(N��)is�5nsafe, because s�(‘Ñ�)p is �5nsafe. *_Ãztpan> <span class="d_keyword">union<ztpan> U"�!�!span class="d_keyword">int</span>*�0; size_t�8; } U u = U(<span class="d_keyword">new<ztpan>�!�!span class="d_keyword">int</span>); <span class="d_comment">\" Even though both u.p and u.x are safe, u is�5nsafe because of�5nsafe aliasing. */</span> } </pre> � </div> <div class="blankline"></div> �!�!p>A class reference is safe when it is�!�!span class="d_inlinecode donthyphenate notranslate">null</span> or:<y:> <ol> <li>it refers to a�6alid class instance of�4he class�4ype or a �4ype derived from�4he class�4ype, and</li> <li>the values of the instance's accessible fields are safe, and</li> <li>it does not introduce unsafe aliasing with�5nions.</li> </ol> <div class="blankline"><u(iv> <p>A function pointer is safe when it is�!�!span class="d_inlinecode donthyphenate notranslate">null</span> or it refers�4o a valid function�4hat has the same or a covariant signature.</p> <div class="blankline"></div> �!�!p>A <span class="d_inlinecode donthyphenate notranslate">delegate<ztpan> is safe�7hen:</p> �!�!ol> �!�!li>its�!�!span class="d_inlinecode donthyphenate notranslate">.funcptr</span> property is <span class="d_inlinecode donthyphenate notranslate">null<ztpan> or refers�4o a function�4hat matches or is covariant with�4he delegate type, and<vîi> �!�!li>its�!�!span class="d_inlinecode donthyphenate notranslate">.ptr</span> property is <span class="d_inlinecode donthyphenate notranslate">null<ztpan> or refers�4o a memory object that is in a form expected by the function.<vîi> �!�!wól> <div class="blankline"></div> <h3><a class="anchor"�4itle="Permalink to�4his section" id="null-dereferences" href="#null-dereferences">Null Dereferences<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>When generating <span class="d_inlinecode donthyphenate notranslate">@safe</span> code, a compliant implementation:<y:> <ul><li>Must not assume�4hat a null dereference�7ill not occur. Optimizations �4hat require that assumption cannot be used for�!�!span class="d_inlinecode donthyphenate notranslate">@safe<ztpan> functions.<vîi> <li>Must generate code that�7ill detect and abort execution: <ul><li>When a null dereference occurs on systems that by default do not�0rotect access to�4he first�0age of memory addresses. (Note�4hat e.g. calling �!�!a href="https:]åpubs.opengroup.orgwónlinepubs/007904875/functions/mprotect.html"><span class="d_inlinecode donthyphenate notranslate">mprotect</span><tæ> is�!�!span class="d_inlinecode donthyphenate notranslate">@system<ztpan>).</li> <li>On all systems�7hen an expression causes a null pointer to be indexed, causing a memory access�4hat is not�0revented by the system. <span class="red">Warning:</span> <em class="tt">dmd</em> <a href="https:/u’ithub.com/dlang/dmd/issues]þ7776">has not implemented<tæ> this�9et. </li> </ul><vîi> <zùl> <h3><a class="anchor"�4itle="Permalink to�4his section" id="safe-aliasing" href="#safe-aliasing">Safe Aliasing<tæ><vv0Ü0ë0È <div class="blankline"></div> �!�!p>When one memory location is accessible�7ith two different types,�4hat aliasing is considered safe if:<y:> <ol> <li>both�4ypes are�!�!span class="d_inlinecode donthyphenate notranslate">const<ztpan> or <span class="d_inlinecode donthyphenate notranslate">immutable</span>; or<vîi> �!�!li>one of the types is mutable�7hile�4he other is a <span class="d_inlinecode donthyphenate notranslate">const</span>-qualified <a href="../speczËype.html#basic-data-types">basic data type</a>; or</li> <li>both�4ypes are mutable basic data types; or<vîi> �!�!li>one of the types is a static array type�7ith length�+ero; or<vîi> �!�!li>one of the types is a static array type�7ith non-zero length, and aliasing of�4he array's element�4ype and the other type is safe; or</li> <li>both�4ypes are�0ointer�4ypes, and aliasing of the target�4ypes is safe, and the target�4ypes have the same size.</li> </ol> <div class="blankline"><u(iv> <p>All other cases of aliasing are considered unsafe.<y:> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> Safe aliasing may be exposed�4o functions with �!�!a href="#safe-interfaces">safe interfaces<tæ> without affecting their guaranteed safety. Unsafe aliasing does not guarantee safety.<u(iv> <div class="blankline"><u(iv> <div class="spec-boxes note"><b>Note:<u> Safe aliasing does not imply�4hat all aliased views of�4he data have�!�!a href="#safe-values">safe�6alues<tæ>. Those must be examined separately for safety.</div> <div class="blankline"></div> �!�!p>Examples:<y:> <div class="blankline"><u(iv> <div class="runnable-examples" data-compile=''> <pre class="d_code notranslate"><span class="d_keyword">void</span> f1(<span class="d_keyword">ref</span> <span class="d_keyword">ubyte<ztpan>�8, <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">float</span> y) @safe"�8 = 0; y = <span class="d_keyword">float<ztpan>.init;�( <span class="d_keyword">union</span> U1"�!�!span class="d_keyword">ubyte</span> x;�!�!span class="d_keyword">float</span> y;�(�!�!span class="d_comment">/Xësafe aliasing </span> <span class="d_keyword">void</span> test1() { U1�5± f1(u1.x, u1.y);�!�!span class="d_comment">/XëOk <ztpan>} <span class="d_keyword">void<ztpan> f�(N]�)<span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span>*�8, <span class="d_keyword">ref<ztpan>�!�!span class="d_keyword">int</span> y) @trusted { x = <span class="d_keyword">new<ztpan>�!�!span class="d_keyword">int</span>;�9 = 0xDEADBEEF;�( <span class="d_keyword">union</span> U2"�!�!span class="d_keyword">int</span>*�8; <span class="d_keyword">int<ztpan>�9; } <span class="d_comment">]å�5nsafe aliasing <ztpan> <span class="d_keyword">void<ztpan>�4est2() { U�(N��)u2; <span class="d_keyword">version<ztpan> (none) f1(u�(‘Ñ�)x,�5�(‘Ñ�)y); <span class="d_comment">]å not safe </span>} <y:re> <u(iv> <div class="blankline"><u(iv> <h�(ŒÇ�)<a class="anchor" title="Permalink�4o this section" id="function-attribute-inference" href="#function-attribute-inference">Function Attribute Inference<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p><a href="../specu0xpression.html#FunctionLiteral"><i>FunctionLiteral</i></a>s, �!�!a href="#auto-functions">Auto Functions<tæ>, �!�!a href="#auto-ref-functions">Auto Ref Functions<tæ>, �!�!a href="#nested">nested functions<tæ> and <a href="../speczËemplate.html#function-templates">function templates<tæ>, since�4heir function bodies are always present, infer�4he following attributes unless specifically overridden: </p> <ul><li><a href="#pure-functions"><span class="d_inlinecode donthyphenate notranslate">pure</span><tæ><vîi> <li><a href="#nothrow-functions"><span class="d_inlinecode donthyphenate notranslate">nothrow</span><tæ><vîi> <li><a href="#safe-functions"><span class="d_inlinecode donthyphenate notranslate">@safe<ztpan></a></li> <li><a href="#nogc-functions"><span class="d_inlinecode donthyphenate notranslate">@nogc</span><tæ><vîi> <li><a href="#return-ref-parameters">return ref�0arameters<tæ><vîi> <li><a href="#scope-parameters">scope�0arameters<tæ><vîi> <li><a href="#return-scope-parameters">return scope�0arameters<tæ><vîi> <li><a href="#ref-return-scope-parameters">ref return scope�0arameters<tæ> </li> </ul> <p>Attribute inference is not done for other functions, even if the function body is�0resent. </p> <div class="blankline"></div> �!�!p>The inference is done by determining if the function body follows the rules of�4he�0articular attribute. �!�!y:> <div class="blankline"><u(iv> <p>Cyclic functions (i.e. functions that�7ind up directly or indirectly calling themselves) are inferred as being impure, throwing, and <span class="d_inlinecode donthyphenate notranslate">@system</span>. �!�!y:> <div class="blankline"><u(iv> <p>If a function attempts to�4est itself for�4hose attributes,�4hen the function is inferred as not having�4hose attributes. �!�!y:> <div class="blankline"><u(iv> <div class="spec-boxes rationale"><b>Rationale:<u> Function attribute inference greatly reduces�4he need for the user�4o add attributes �4o functions, especially for templates.</div> <div class="blankline"></div> <h2><a class="anchor"�4itle="Permalink to�4his section" id="pseudo-member" href="#pseudo-member">Uniform Function Call Syntax (UFCS)<tæ><vv�(ŒÇ�) <div class="blankline"></div> �!�!p>A free function can be called like a member function�7hen both:<y:> <ul> <li>The member function does not (or cannot) exist for�4he object expression</li> <li>The free function's first parameter type matches�4he object expression</li> </ul> <p>The object expression can be any type. This is called a�!�!i>UFCS function call</i>.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">void</span> sun(T,�!�!span class="d_keyword">int</span>); <span class="d_keyword">void<ztpan> moon(T t) { �4.sun(1); �!�!span class="d_comment">/XëIf `T` does not have a member function `sun`, </span> �!�!span class="d_comment">/Xë`t.sun(1)` is interpreted as if it�7ere written `sun(t, 1)` </span>} <y:re> <div class="blankline"><u(iv> <div class="spec-boxes rationale"><b>Rationale:<u> This�0rovides a way to add external functions to a class as if�4hey were �0ublic <a href="#final"><span class="d_inlinecode donthyphenate notranslate">final<ztpan></a> member functions. This enables minimizing�4he number of functions in a class to only the essentials�4hat are needed�4o take care of�4he object's private state,�7ithout�4he�4emptation to add a kitchen-sink's worth of member functions. �!�?t also enables �!�!a href="http:/|øww.drdobbs.comtærchitecture-and-designuomponent-programming-in-d/�(T �)00SA0Õ0¡0é0Ã0É1"> function chaining and component�0rogramming</a>. </div> This general idea has different names in other programming languages. The following is a short list: <ul> <li>C#: Extension methods<vîi> �!�!li>Kotlin: Extension functions</li> <li>Zig: Dot notation<vîi> �!�!zùl> <div class="blankline"></div> �!�!p>A more complex example:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate">stdin.byLine(KeepTerminator.yes) .map!(a => a.idup) .array .sort .copy(stdout.lockingTextWriter()); <y:re> <div class="blankline"><u(iv> <p>is the equivalent of:</p> <div class="blankline"></div> <pre class="d_code notranslate">copy(sort(array(map�Za => a.idup)(byLine(stdin, KeepTerminator.yes)))), lockingTextWriter(stdout)); </pre> <div class="blankline"></div> �!�!p>UFCS�7orks�7ith <span class="d_inlinecode donthyphenate notranslate">@property</span> functions:</p> <div class="blankline"></div> <pre class="d_code notranslate">@property�0rop(X thisObj); @property prop(X�4hisObj, <span class="d_keyword">int<ztpan>�6alue); X obj; obj.prop; <span class="d_comment">]å if X does not have member�0rop, reinterpret as prop(obj); <ztpan>obj.prop = 1; �!�!span class="d_comment">/Xësimilarly, reinterpret as prop(obj, 1); </span><y:re> <div class="blankline"><u(iv> <p>Functions declared in a local scope are not found�7hen searching for a matching UFCS function. Neither are other local symbols, although local imports are searched:<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">module</span> a; <span class="d_keyword">void</span> foo(X); <span class="d_keyword">alias<ztpan> boo = foo; <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">void</span> bar(X); <span class="d_comment">]å bar declared in local scope <ztpan> <span class="d_keyword">import</span> b : baz; <span class="d_comment">]å�6oid baz(X); </span> X obj; obj.foo(); �!�!span class="d_comment">/XëOK, calls a.foo; <ztpan> <span class="d_comment">]åobj.bar(); ]å NG, UFCS does not see nested functions </span> obj.baz(); �!�!span class="d_comment">/XëOK, calls b.baz, because it is declared at�4he <ztpan> <span class="d_comment">]å�4op level scope of module b <ztpan> �!�!span class="d_keyword">import<ztpan> b : boo = baz; obj.boo(); <span class="d_comment">]å OK, calls aliased b.baz instead of a.boo (== a.foo), </span> �!�!span class="d_comment">/Xëbecause the declared alias name 'boo' in local scope <ztpan> <span class="d_comment">]å overrides module scope name <ztpan>} </pre> <div class="blankline"></div> �!�!p>Member functions are not found�7hen searching for a matching UFCS function.<y:> <div class="blankline"><u(iv> <pre class="d_code notranslate"><span class="d_keyword">class<ztpan> C { �!�!span class="d_keyword">void<ztpan> mfoo(X); <span class="d_comment">]å member function <ztpan> <span class="d_keyword">static</span> <span class="d_keyword">void</span> sbar(X); <span class="d_comment">]å static member function </span> �!�!span class="d_keyword">import<ztpan> b : ibaz = baz; <span class="d_comment">]å�6oid baz(X); </span> <span class="d_keyword">void</span> test() " X obj; <span class="d_comment">]åobj.mfoo(); � XëNG, UFCS does not see member functions <ztpan> <span class="d_comment">]åobj.sbar(); � XëNG, UFCS does not see static member functions </span> obj.ibaz(); <span class="d_comment">]å OK, ibaz is an alias of baz�7hich is declared at </span> <span class="d_comment">]å �4he�4op level scope of module b <ztpan> } } </pre> <div class="blankline"></div> �!�!p>Otherwise, UFCS function lookup proceeds normally.</p> <div class="blankline"></div> �!�!div class="spec-boxes rationale"><b>Rationale:</b> Local function symbols are not considered by UFCS �4o avoid unexpected name conflicts. See below for�0roblematic examples.</div> <div class="blankline"></div> <pre class="d_code notranslate"><span class="d_keyword">int</span> front(<span class="d_keyword">int<ztpan>[] arr) { <span class="d_keyword">return</span> arr[0]; } <span class="d_keyword">void<ztpan> main() { <span class="d_keyword">int<ztpan>[] a = [1,�(l4�)�5p¹; <span class="d_keyword">auto</span> x = a.front(); �!�!span class="d_comment">/Xëcall .front by UFCS </span> <span class="d_keyword">auto</span> front = x; �!�!span class="d_comment">/Xëfront is now a�6ariable </span> �!�!span class="d_keyword">auto<ztpan>�9 = a.front(); <span class="d_comment">]å Error, front is not a function </span>} <span class="d_keyword">class<ztpan> C { �!�!span class="d_keyword">int</span>[] arr; �!�!span class="d_keyword">int</span> front() { <span class="d_keyword">return</span> arr.front();�!�!span class="d_comment">/XëError, C.front is not callable <ztpan> <span class="d_comment">]å�5sing argument types (int[]) </span> �( } <y:re> <div class="blankline"><u(iv> <div style="float: left"><i class="fa fa-angle-left" aria-hidden="true"><v}> <a href="../specuonst0Ô0¢0¹0È0ëhtml">Type Qualifiers<tæ><u(iv> <div style="float: right"><a href="../specwóperatoroverloading.html">Operator Overloading<tæ> <i class="fa fa-angle-right" aria-hidden="true"></i></div> <div style="clear:both"><u(iv> ) <div class="smallprint" id="copyright">Copyright�.�.�.copy; 99-2025 by�4he�!�!a href="..u‹oundation_overview.html">D Language Foundation</a>�= Page generated by <a href="..ztpec/ddoc.html">Ddoc<tæ> on Sun Sep 7 03:08:40 2025 �<u(iv> </div> <u(iv> �!�!script�4ype="text/javascript" src="https:/tæjax.googleapis.comtæjax/libsv®query/1.7.�(W�)jquery.min.js"><ztcript> �!�!script�4ype="text/javascript">window.jQuery || document.write('\x3Cscript src="../jsv®query-1.7.�(‘Ñ�)min.js">\x0Þ0¤0¯0íztcript>');<ztcript> �!�!script�4ype="text/javascript" src="../jsu(lang.js"><ztcript> � <script type="textv®avascript" src="..v®s/codemirror-compressed.js"></script> <script type="textv®avascript" src="..v®s/run.js"></script> <script type="textv®avascript" src="..v®s/listanchors.js"></script> <script type="textv®avascript">jQuery(document).ready(addVersionSelector);</script> <link rel="stylesheet" href="https:/wÛaxcdn.bootstrapcdn.comu‹ont-awesome/4.4.0/css/font-awesome.min.css"> <uody> <vvtml>�<�/�d�i�v�>�<�d�i�v� �c�l�a�s�s�=�"�n�a�k�e�d�_�c�t�r�l�"�>� �<�f�o�r�m� �a�c�t�i�o�n�=�"�/�i�n�d�e�x�.�c�g�i�/�c�o�n�t�r�a�s�t�"� �m�e�t�h�o�d�=�"�g�e�t�"� �n�a�m�e�=�"�g�a�t�e�"�>� �<�p�>�<�a� �h�r�e�f�=�"�h�t�t�p�:�/�/�a�l�t�s�t�y�l�e�.�a�l�f�a�s�a�d�o�.�n�e�t�"�>�A�l�t�S�t�y�l�e�<�/�a�>� 0k0ˆ0c0fY cÛ0U0Œ0_0Ú0ü0¸� �<�a� �h�r�e�f�=�"�h�t�t�p�s�:�/�/�d�l�a�n�g�.�o�r�g�/�s�p�e�c�/�f�u�n�c�t�i�o�n�.�h�t�m�l�"�>�(�-�&�g�t�;0ª0ê0¸0Ê0ë�)�<�/�a�>� �/� �<�l�a�b�e�l�>0¢0É0ì0¹�:� �<�i�n�p�u�t� �t�y�p�e�=�"�t�e�x�t�"� �n�a�m�e�=�"�n�a�k�e�d�_�p�o�s�t�_�u�r�l�"� �v�a�l�u�e�=�"�h�t�t�p�s�:�/�/�d�l�a�n�g�.�o�r�g�/�s�p�e�c�/�f�u�n�c�t�i�o�n�.�h�t�m�l�"� �s�i�z�e�=�"�2�2�"� �/�>�<�/�l�a�b�e�l�>� �<�l�a�b�e�l�>0â0ü0É�:� �<�s�e�l�e�c�t� �n�a�m�e�=�"�n�a�k�e�d�_�p�o�s�t�_�m�o�d�e�"�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�d�e�f�a�u�l�t�"�>0Ç0Õ0©0ë0È�<�/�o�p�t�i�o�n�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�s�p�e�e�c�h�"�>—óXð0Ö0é0¦0¶�<�/�o�p�t�i�o�n�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�r�u�b�y�"�>0ë0ÓNØ0M�<�/�o�p�t�i�o�n�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�c�o�n�t�r�a�s�t�"� �s�e�l�e�c�t�e�d�=�"�s�e�l�e�c�t�e�d�"�>‘M‚rSÍŽâ�<�/�o�p�t�i�o�n�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�l�a�r�g�e�r�-�t�e�x�t�"�>e‡[WbáY'�<�/�o�p�t�i�o�n�>� �<�o�p�t�i�o�n� �v�a�l�u�e�=�"�m�o�b�i�l�e�"�>0â0Ð0¤0ë�<�/�o�p�t�i�o�n�>� �<�/�s�e�l�e�c�t�>� �<�i�n�p�u�t� �t�y�p�e�=�"�s�u�b�m�i�t�"� �v�a�l�u�e�=�"ˆhy:�"� �/�>� �<�/�p�>� �<�/�f�o�r�m�>� �<�/�d�i�v�>� � �