Best practice - Declarations and assignments on global and local scopes. Pros and cons?

Some programs usually recommend not using global variables and declarations, but rather only use them in local scopes. Is there recommended approach to these?

Should it be limited to globally declare variables, but not assigning values to them and do the necessary things inside procedures to affect those global variables?

There’s no reason to avoid global variables as long as you know how you are using them.

  • If you only have a single thread, it’s perfectly fine.
  • If you have multiple threads but you use some form of synchronisation (mutex, atomics) they are also fine.
  • If you have multiple threads but the data is only ever read, they are fine as well.

And here’s the kicker… even if you scope them, you should still know how you are using them. Just because you scope e.g. a [dynamic]T it doesn’t become thread safe. Actually, if you keep passing around a ^[dynamic]T it would even become worse if it goes out of scope and you delete the array it points to.

Regarding initialization, if you know everything at compile time I’d just write it out if the compiler allows it, otherwise use an @(init) proc to populate the data on startup (of course assuming you can init it before the runtime even calls main ).

In general, it’s just bad if you init globals from all sorts of different procs at runtime. If you ever need to move code around, you can easily break assumptions on when a global can be accessed.

1 Like

Hmmm… So far I don’t think I have come across something that would generally need global variable. Probably some structs that work as passing data from one procedure to another. X11 window, surface and Vulkan/OpenGL instancing can be handled in main procedure scope.

The first thing that comes to mind is static look up tables for e.g. stream decoding/decompression. :slightly_smiling_face:
You don’t necessarily want to have a large table instantiated on the stack of many-many threads.