Variables are never allowed to shadow identifiers from an outer scope.
It is generally preferable to use rather than var
when declaring a variable. This causes less work for both humans and computers to do when reading code, and creates more optimization opportunities.
Global variables are considered to be a top level declaration, which means that they are order-independent and lazily analyzed. The initialization value of global variables is implicitly comptime. If a global variable is const
then its value is comptime
-known, otherwise it is runtime-known.
global_variables.zig
$ zig test global_variables.zig
All 1 tests passed.
namespaced_global.zig
$ zig test namespaced_global.zig
1/1 test "namespaced global variable"... OK
The extern
keyword can be used to link against a variable that is exported from another object. The export
keyword or builtin function can be used to make a variable available to other objects at link time. In both cases, the type of the variable must be C ABI compatible.
See also:
A variable may be specified to be a thread-local variable using the threadlocal
keyword:
$ zig test tls.zig
1/1 test "thread local storage"... OK
All 1 tests passed.
For Single Threaded Builds, all thread local variables are treated as .
Thread local variables may not be const
.
Local variables occur inside Functions, blocks, and @cImport blocks.
When a local variable is const
, it means that after initialization, the variable’s value will not change. If the initialization value of a variable is -known, then the variable is also comptime
-known.
comptime_vars.zig
$ zig test comptime_vars.zig
All 1 tests passed.