Search⌘ K
AI Features

Name Scopes

Explore the concept of name scopes in D programming to understand where variables are accessible within your code. Learn why defining variables near their first use enhances code speed, readability, and maintenance. This lesson guides you in managing scopes to avoid errors and maintain clean, efficient D programs.

Name scope

Any name is accessible from the point where it has been defined to the point where its scope ends, as well as in all of the scopes that its scope includes. In this regard, every scope defines a name scope.
Names are not available beyond the end of their scope:

D
import std.stdio;
void main() {
bool aCondition = true;
int outer;
if (aCondition) { // ← curly bracket starts a new scope
int inner = 1;
outer = 2; // ← 'outer' is available here
} // ← 'inner' is not available beyond this point
inner = 3; // ← compilation ERROR
// 'inner' is not available in the outer scope
}

Because inner is defined within the scope of the if condition, it is available only in that scope. On the other hand, outer is available in both the if block scope and main function scope.

It is not legal to define the same name in an inner scope:

size_t length = oddNumbers.length;

if (aCondition) {
    size_t length = primeNumbers.length; // ← compilation ERROR 
}
...