Skip to content

Commit

Permalink
docs(general): Document that static variables cannot be defined condi…
Browse files Browse the repository at this point in the history
…tionally

YoYoGames/GameMaker-Bugs#4449

(cherry picked from commit 87b8eb5)
  • Loading branch information
gurpreetsinghmatharoo committed Aug 8, 2024
1 parent eac8fae commit 1f32f99
Showing 1 changed file with 2 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ <h1><span data-field="title" data-format="default">Static Variables</span></h1>
<p>If you didn&#39;t use the <span class="inline2">static</span> keyword here the output would simply be <span class="inline2">0</span> for every iteration of the loop, since the variable <span class="inline2">num</span> will be getting defined as <span class="inline2">0</span> every time the function is called before being returned.</p>
<h3>Initialisation Order</h3>
<p>When a function is called, its static variables are initialised first, before the rest of the function body is executed.</p>
<p>This mean it&#39;s possible to access a static variable before the line where it&#39;s defined, as the static variable would have already been initialised, even in the first call:</p>
<p>This mean it&#39;s possible to access a static variable before the line where it&#39;s defined, as it would have already been initialised, even in the first call:</p>
<p class="code">function static_test()<br />
{<br />
    show_debug_message(static_variable);<br />
    static static_variable = 1000;<br />
}</p>
<p>However, it is not recommended to do this, and <a data-xref="{title}" href="../../../Setting_Up_And_Version_Information/IDE_Preferences/Feather_Settings.htm">Feather</a> will show a GM2043 warning if you try to access a static variable before its initialisation line.</p>
<p>This also means you cannot have conditionally defined static variables, as they will always exist throughout the function body. For example, if you have a static variable initialised inside an <span class="inline2">if</span> condition block, it will be initialised at the top regardless of the condition&#39;s result.</p>
<h2>Statics with Constructors</h2>
<p>You can also use static variables in <a href="../Structs.htm#constr">constructor functions</a>. These functions are used to create new structs that contain the variables defined within the function.</p>
<p>Static variables in constructors are only initialised once for that constructor, and <strong>they are not duplicated</strong> for each new struct made from the constructor.</p>
Expand Down

0 comments on commit 1f32f99

Please sign in to comment.