This is an automated archive made by the Lemmit Bot.

The original was posted on /r/programminglanguages by /u/igors84 on 2024-10-16 17:11:45+00:00.


I am trying myself in language design and today I started thinking: why do we need global variables? Since “global” might mean many things I should clarify that I mean variables which exists during entire program duration and are accessible from multiple functions. They may be only accessible to a single file/module/package but as soon as more than one function can access it I call it a global.

In some languages you can define a variable that exists during the entire program duration but is only accessible from one function (like static variable defined within function body in C) and I do not include those in my definition of a global.

So if a language doesn’t allow you to define that kind of global variables can you tell me some examples that would become impossible or significantly harder to implement?

I could only think of one useful thing. If you want to have a fixed buffer to use instead of having to call some alloc function you can define a global static array of bytes of fixed size. Since it would be initialized to all zeros it can go into bss segment in the executable so it wouldn’t actually increase its size (since bss segment just stores the needed size and OS program loader will than map the memory to the process on startup).

On the other hand that can be solved by having local scope static variable within a function that is responsible for distributing that buffer to other parts of the program. Or we can define something like @reserveModuleMemory(size) and @getModuleMemory() directives that you can use to declare and fetch such buffer.

Any other ideas?