ArticleslgStudy

computer science

Global variable

Global variable is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Global variable rather than just read about it. In short: In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.

Key takeaways

  • Global variable belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Global variable to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Global variable from memory before moving on to harder problems.

Reference excerpt

In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state. In compiled languages, global variables are generally static variables, whose extent (lifetime) is the entire runtime of the program, though in interpreted languages (including command-line interpreters), global variables are generally dynamically allocated when declared, since they are not known ahead of time. In some languages, all variables are global, or global by default, while in most modern languages variables have limited scope, generally lexical scope, though global variables are often available by declaring a variable at the top level of the program. In other languages, however, global variables do not exist; these are generally modular programming languages that enforce a module structure, or class-based object-oriented programming languages that enforce a class structure.

Use Interaction mechanisms with global variables are called global environment (see also global state) mechanisms. The global environment paradigm is contrasted with the local environment paradigm, where all variables are local with no shared memory (and therefore all interactions can be reconducted to message passing). Global variables are used extensively to pass information between sections of code that do not share a caller/callee relation like concurrent threads and signal handlers. Languages (including C) where each file defines an implicit namespace eliminate most of the problems seen with languages with a global namespace though some problems may persist without proper encapsulation. Without proper locking (such as with a mutex), code using global variables will not be thread-safe except for read only values in protected memory.

Global-only and global-by-default A number of non-structured languages, such as (early versions of) BASIC, COBOL and Fortran I (1956) only provide global variables. Fortran II (1958) introduced subroutines with local variables, and the COMMON keyword for accessing global variables. Usage of COMMON in FORTRAN continued in FORTRAN 77, and influenced later languages such as PL/SQL. Named COMMON groups for globals behave somewhat like structured namespaces. Variables are also global by default in Forth, Lua, Perl, and most shells.

By language

C and C++ The C language does not have a global keyword. However, variables declared outside a function have "file scope," meaning they are visible within the file. Variables declared with file scope are visible between their declaration and the end of the compilation unit (.c file) (unless shadowed by a like-named object in a nearer scope, such as a local variable); and they implicitly have external linkage and are thus visible to not only the .c file or compilation unit containing their declarations but also to every other compilation unit that is linked to form the complete program. External linkage, however, is not sufficient for such a variable's use in other files: for a compilation unit to correctly access such a global variable, it will need to know its type. This is accomplished by declaring the variable in each file using the extern keyword. (It will be declared in each file but may be defined in only one.) Such extern declarations are often placed in a shared header file, since it is common practice for all .c files in a project to include at least one .h file: the standard header file errno.h is an example, making the errno variable accessible to all modules in a project. Where this global access mechanism is judged problematic, it can be disabled using the static keyword which restricts a variable to file scope, and will cause attempts to import it with extern to raise a compilation (or linking) error. An example of a "global" variable in C:

As the variable is an external one, there is no need to pass it as a parameter to use it in a function besides main. It belongs to every function in the module. The output will be:

3 5 5 5

Java Some languages, like Java, don't have global variables. In Java, all variables that are not local variables are fields of a class. Hence all variables are in the scope of either a class or a method. In Java, static fields (also known as class variables) exist independently of any instances of the class and one copy is shared among all instances; hence public static fields are used for many of the same purposes as global variables in other languages because of their similar "sharing" behavior:

PHP PHP has a global keyword and a number of unusual ways of using global variables. Variables declared outside functions have file scope (which is for most purposes the widest scope). However, they are not accessible inside functions unless imported with the global keyword (i.e., the keyword accesses global variables, it does not declare them). However, some predefined variables, known as superglobals are always accessible. They are all arrays. A general purpose one is the $GLOBALS superglobal, which contains all the variables defined out of function scope. Changes to its elements change the original variables, and additions create new variables. The superglobals $_POST and $_GET are widely used in web programming.

Other languages In Python and MATLAB a global variable can be declared anywhere with the global keyword. Ruby's global variables are distinguished by a '$' sigil. A number of predefined globals exist, for instance $$ is the current process ID.

See also Local variable Non-local variable Singleton pattern Variables Static variable Dynamic variable External variable

References

Worked examples

Example 1 — a first encounter with Global variable

Start with the simplest possible case. Write down what Global variable claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Global variable before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Global variable ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Global variable

In research
Global variable appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Global variable in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Global variable is common in secondary-school and first-year university syllabi. It links to neighbouring topics Variable (computer science), so understanding it makes those chapters shorter.
In everyday life
Look for Global variable outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Global variable” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Global variable in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Global variable means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Global variable out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Global variable in simple terms?

In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.

Why does Global variable matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Global variable?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Global variable.

Tags

  • Variable (computer science)

Keep exploring