Local static variables must have unique names within a function's scope.

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Jan 19 18:11:36 UTC 2018


On Fri, Jan 19, 2018 at 02:16:24PM +0000, tipdbmp via Digitalmars-d-learn wrote:
> > Mostly, it's just a bad idea - it's very easy for a person reading
> > the code after you've written it to get the two x's mixed up.
> 
> // example from: 19.17.1.3
> void main()
> {
>     { static int x; }
>     { static int x; } // error
>     { int i; }
>     { int i; } // ok
> }
> 
> I don't really see how the 'static' storage class would make 2
> variables with the same name in different scopes "easier to mix up"
> compared to 2 variables with the same name in different scopes but
> declared without the 'static' keyword.

I think this is more an implementational quirk than any deliberate
decision on variable names being "easier to mix up".  A static variable
currently mangles to a combination of the function name and variable
name, so if there are multiple static variables with the same name,
their mangled names would collide.

OTOH, it would really suck if non-static variable names can't be reused
in nested scopes, because it would mean you have to invent new names
for, say, loop variables for every loop in the same function:

	void func(int[100] a, int[100] b) {
		foreach (i; 0 .. 100) { a[i] = i; }
		foreach (i; 0 .. 100) { b[i] = i; } // this would fail
	}

Fortunately this is not the case.  However, the static variable case is
annoying, and it's actually one case of a larger problem:

	void main() {
		foreach (i; 0 .. 10) {
			struct S {
				int x;
			}
			auto s = S(i);
		}
		foreach (i; 11 .. 20) {
			struct S { // <---- this is line 9
				int y;
			}
			auto s = S(i);
		}
	}

The compiler says:

	test.d(9): Error: declaration S is already defined in another scope in main

even though the respective scopes of the declarations are disjoint. IMO,
this is a needless, arbitrary restriction. Worse yet, the compiles ICEs
after this, so I filed a bug:

	https://issues.dlang.org/show_bug.cgi?id=18266


T

-- 
Latin's a dead language, as dead as can be; it killed off all the Romans, and now it's killing me! -- Schoolboy


More information about the Digitalmars-d-learn mailing list