What is global variable in C programming?
A global variable is a variable that is declared at global
scope, rather than file, namespace, function, class or nested
scope. Global variables are usually declared with external linkage
within a header and initialised in one (and only one) source file.
Any file that includes the header (which includes the source file
that initialised the global variable) then has unrestricted access
to the variable. It is globally visible and any code can alter
it.
Global variables should be used sparingly and only when
absolutely necessary. If the vast majority of the functions in your
program require access to a particular variable, then a global
variable makes perfect sense and is by far the simplest solution.
However, a variable that is only used by a handful of functions can
hardly be described as a global entity, thus it has no place within
the global namespace and should be scoped to those functions that
actually require it instead.