GLSL For-Loop Variable Scoping Rules

In the OpenGL Shading Language (GLSL), the scope of a loop index variable declared directly within a for-loop header is strictly confined to the loop construct itself. This article details how the GLSL specification governs the visibility, lifetime, and shadowing behavior of loop index variables, ensuring safe memory use and deterministic shader compilation.

Scope Boundary

When a variable is declared within the initialization clause of a for statement (for example, for (int i = 0; i < 10; ++i)), its scope begins immediately following its declaration and terminates at the conclusion of the loop's controlled statement or block.

Consequently, the variable is accessible in:

  • The condition expression (e.g., i < 10)
  • The loop iteration expression (e.g., ++i)
  • The loop body (the single statement or compound block enclosed in {})

Once the loop terminates, the index variable goes out of scope and ceases to exist. Any reference to this variable outside the loop header or body results in a compilation error.

Variable Shadowing

If a variable declared in the for-loop header shares the name of an existing variable in an outer enclosing scope, the loop index variable shadows the outer variable.

Within the loop body, any reference to the identifier resolves strictly to the locally declared loop index. The outer variable remains unaltered and becomes accessible again only after the loop completes and its local scope exits.

Sequential Loops and Re-declaration

Because the scope of the index variable is confined to the for loop, you can reuse the same identifier in subsequent sibling loops within the same function or block:

// First loop: 'i' exists only here
for (int i = 0; i < 4; ++i) {
    // Process data
}

// Second loop: Valid; a new 'i' is declared with its own scope
for (int i = 0; i < 8; ++i) {
    // Process data
}

// Compilation error: 'i' is undeclared in this scope
// int result = i; 

Nested Loops

In nested loops, declaring an inner loop index with the same identifier as the outer loop index causes the inner variable to shadow the outer variable for the duration of the nested block. While legal in GLSL, this practice is discouraged to avoid logic errors where the outer loop's progression relies on an index that has been obscured.