What is 'scope' in function parameter?

Mike Franklin slavo5150 at yahoo.com
Tue Dec 26 00:17:33 UTC 2017


On Monday, 25 December 2017 at 10:42:55 UTC, Sobaya wrote:

> ```
> import std.stdio;
>
> int[] x;
>
> void func(scope int[] a) {
>     x = a;
> }
>
> void main() {
>     func([0,1,2]);
>     writeln(x);
> }
> ```
>
> This code was successfully compiled and printed '[0, 1, 2]'.
>
> But according to https://dlang.org/spec/function.html, above 
> code must cause a compile error.
>

After a few hours trying to figure out why the compiler didn't 
catch this, I finally figured it out.  You have to add `@safe`.

import std.stdio;

int[] x;

void func(scope int[] a) @safe
{
     x = a;
}

void main() @safe {
     func([0,1,2]);
     writeln(x);
}

This is one of the things really ticks me off about D; it has all 
the wrong defaults.

At a minimum, the documentation needs clarification.  I encourage 
you to file a  bug report against the documentation at 
http://issues.dlang.org/

Mike



More information about the Digitalmars-d-learn mailing list