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

Simen Kjærås simen.kjaras at gmail.com
Fri Jan 19 11:40:22 UTC 2018


On Friday, 19 January 2018 at 11:02:01 UTC, tipdbmp wrote:
> The following seems to work in C++, but errors in D, why is 
> that?
>
> int foo(int* num) {
>     {
>         static int x = 10;
>         x += 1;
>         *num += x;
>     }
>
>     {
>         static int x = 20; // error: foo.x is already defined 
> in another scope in foo
>         x += 2;
>         *num += x;
>     }
>
>     return 0;
> }
>
> https://dlang.org/spec/function.html#local-static-variables

19.17.1.3 explains the fact that they need to have unique names, 
but doesn't provide a reason. 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.

--
   Simen


More information about the Digitalmars-d-learn mailing list