Bug 23579 – static locals cannot be initialized with stack locals

Status
RESOLVED
Resolution
WONTFIX
Severity
normal
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2022-12-26T04:45:00Z
Last change time
2023-07-14T21:15:15Z
Assigned to
No Owner
Creator
Basile-z

Comments

Comment #0 by b2.temp — 2022-12-26T04:45:00Z
The semantics of static locals should be changed to allow ttheir initialization with stack locals or parameters. For example, the following example does not compile ``` void v(int a) { static int b = a; } ``` because > test.d:3:20: Error: variable `a` cannot be read at compile time but that should be accepted because it is equivalent to ``` void v(int a) { static int b; b = a; } ``` as `b` is only visible in `v` scope.
Comment #1 by nick — 2022-12-26T10:41:52Z
Assignment is not initialization. A static variable is only initialised once. What is your use case? In the example b's previous value is discarded every time v is called, so why is b static?
Comment #2 by b2.temp — 2022-12-26T12:56:55Z
I have no use case, it's just something that I've noticed and that I find odd.
Comment #3 by maxsamukha — 2022-12-26T13:48:02Z
(In reply to Nick Treleaven from comment #1) > Assignment is not initialization. A static variable is only initialised > once. What is your use case? In the example b's previous value is discarded > every time v is called, so why is b static? The initialization vs assignment distinction is useless, given the requirement that T.init is a valid value of T.
Comment #4 by ibuclaw — 2022-12-27T23:47:19Z
C++ supports and implements this by generating the following code: ``` void v(int a) { static bool __guard_for_b = false; static int b = 0; if (__guard_for_b == 0) { b = a; __guard_for_b = true; } } ``` Things get hairier with __gshared variables. ``` void v(int a) { __gshared bool __guard_for_b = false; __gshared int b = 0; if (core.atomic.atomicLoad!(MemoryOrder.acq)(__guard_for_b) == 0) { synchronized // __cxa_guard_acquire(&__guard_for_b) { b = a; __guard_for_b = true; } // __cxa_guard_release(&__guard_for_b) } } ``` I don't think we really need such an expensive run-time feature in D.