samedi 29 février 2020

Is it OK to use global variables when they are only used in one file? Are const/constexpr global variables generally considered OK to use?

I understand that global variables should be avoided whenever possible for a few reasons:

  1. It's hard to debug if a global variable has an invalid value (since every function has access to it)

  2. For multiple global variables over multiple files, if there are any dependencies on the global variables (e.g., if you have a = 1; in one file, and extern a; b = a + 1; in another file), the values of these variables will be undefined since we can't know the order of evaluation of these expressions.

Are const or constexpr global variables generally ok to use? Since they can't be ever be written to, they aren't ever affected by the first point, and constexpr global variables are evaluated before runtime by the compiler, so the second point doesn't apply to them. Also, if you only use const variables in the file they are defined in, the second point won't apply to them either.

Also, there are probably some situations where using non-const global variables is really convenient. Assuming they are only used in one file so the order of evaluation of translation units won't matter, is it worth it to use a small amount of global variables when they really simplify your code? (e.g., you won't have to keep passing local variables by reference to various functions from main).

Aucun commentaire:

Enregistrer un commentaire