On Thursday, 25 February 2016 at 12:18:07 UTC, mahdi wrote:
On Thursday, 25 February 2016 at 11:50:02 UTC, sigod wrote:
On Thursday, 25 February 2016 at 10:03:08 UTC, mahdi wrote:
Thanks.

So when we define the function, we MUST specify the array size to be able to accept a static array? Can't we just define a function which can accept any static array with any size? (e.g. a function to calculate average of a static int array of any size)?

Static array can be accepted in place of dynamic:

        void foo()
        {
                int[3] arr = [1, 2, 3];
                
                bar(arr);
        }
        
        void bar(scope int[] arr)
        {
                import std.stdio : writeln;
                writeln(arr); // [1, 2, 3]
        }

But be careful not to escape such variables. Demonstration: http://dpaste.dzfl.pl/613e04d4fe3f

My question: If in your `bar` function, the code tries to add a new element to the dynamic array, it will be completely ok because array is dynamic. BUT if we pass a static array to this function, can this error be detected at compile time (and prevent a runtime error)? If so, how?

Also, if you need to append elements to an array inside of a function, then you need to mark function arguments as `ref`:

        void bar(ref int[] arr)

Code wouldn't compile if you try to pass static array as `ref` argument.

Error: function f436.bar (ref int[] arr) is not callable using argument types (int[3])

Reply via email to