Static variables inside functions Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
mynameisjohn
Posts: 32
Joined: 27 Mar 2018, 19:38

Static variables inside functions

Post by mynameisjohn » 26 Sep 2021, 18:01

What differs

Code: Select all

MyFunction() {
   static TargetVar, RequestedCapacity = 16
   VarSetCapacity(TargetVar, RequestedCapacity, 0)
   NumPut(RequestedCapacity , TargetVar, 0, "Type")
   DllCall("Function", "Ptr", &TargetVar)
   Flag := NumGet(TargetVar, 8, "Type")
   return Flag
}
from

Code: Select all

MyFunction() {
   RequestedCapacity = 16
   NumPut(RequestedCapacity , TargetVar, 0, "Type")
   VarSetCapacity(TargetVar, RequestedCapacity, 0)
   DllCall("Function", "Ptr", &TargetVar)
   Flag := NumGet(TargetVar, 8, "Type")
   return Flag
}
Does static inside a function implies it will be initialized just once before script begins (or when the function is called)?

Calling a function with static variables multiple times, will assign the variables again?

User avatar
mikeyww
Posts: 26588
Joined: 09 Sep 2014, 18:38

Re: Static variables inside functions

Post by mikeyww » 26 Sep 2021, 18:04

:arrow: Static initializers
Static variables are always implicitly local, but differ from locals because their values are remembered between calls. Each static variable is initialized only once (before the script begins executing).

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Static variables inside functions  Topic is solved

Post by swagfag » 26 Sep 2021, 18:11

top:
  • variable TargetVar is created once and gets a unique address for the lifetime of the script(may or may not be relevant)
  • variable RequestedCapacity is created once, and assigned value 16, and gets a unique address for the lifetime of the script(may or may not be relevant)
  • variable TargetVar is zero-initted every time the function is called

bottom:
  • variable RequestedCapacity is created every time the function is called, and assigned value 16, and gets a unique address every time the function is called(may or may not be relevant)
  • variable TargetVar is created every time the function is called and gets a unique address every time the function is called(may or may not be relevant)
  • variable TargetVar is zero-initted every time the function is called
also ur calls' order makes no sense

Post Reply

Return to “Ask for Help (v1)”