Variables

    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 . If a global variable is const then its value is comptime-known, otherwise it is runtime-known.

    global_variables.zig

    1. $ zig test global_variables.zig
    2. All tests passed.

    namespaced_global.zig

    1. $ zig test namespaced_global.zig
    2. 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 @export 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:

    1. $ zig test tls.zig
    2. 1/1 test "thread local storage"...OK
    3. All tests passed.

    For , all thread local variables are treated as Global Variables.

    Thread local variables may not be const.

    Local variables occur inside , comptime blocks, and 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 comptime-known, then the variable is also comptime-known.

    comptime_vars.zig

    1. $ zig test comptime_vars.zig
    2. All tests passed.