Sign in Join
Wiki copytemporary

Global variables: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Global variables

OldNewLine
1+A [[Variable|variable]] is global if it is exported from a module. This usually refers to variables declared in a [[Var|var section]]
2+
3+- prior any other nested [[Block|block]] in a [[Program|program]], or
4+- in the `interface` part of a [[Unit|unit]].
5+
6+Global variables can be accessed from all other modules that import the exporting modules. Note, however, that a `program` can not be imported.
7+
8+``` pascal
9+program globalVariableDemo(input, output, stdErr);
10+var
11+ x: integer;
12+
13+procedure doMagic;
14+begin
15+ // here, x is global to doMagic
16+end;
17+
18+procedure foo;
19+var
20+ // shadow the global x
21+ x: integer;
22+begin
23+ // here, x is local,
24+ // as the top-scope x can not be accessed
25+end;
26+
27+// MAIN //
28+begin
29+ // here, x is local
30+end.
31+```
32+
33+## remarks
34+
35+If speed matters, global variables are/were used for frequently invoked routines, since allocating [[Local variables|local variables]] on the stack takes time. This, however, is considered bad style. Nest your variables as deep as possible, but as high as necessary.
36+
37+A [[Resourcestring|resourceString variable]] is always global.
38+
39+The [[FPC]] supports thread variables, too. They are sort of half-way between global and local variables. A [[ThreadVar|threadVar variable]] is local to a thread.
40+
41+## see also
42+
43+- [[Scope|Tutorial: Scope]]
44+- [[Singleton Pattern|singleton pattern]]
45+- [Article “Global variable” on the English Wikipedia](https://en.wikipedia.org/wiki/Global_variable)
46+
47+---
48+*From the Free Pascal wiki, page "Global variables", as it stood on 2024-02-21 after a change by Elender, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
49+Category: Code

Back to history