Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Passing static arrays to procedures

We have static arrays with various sizes and we want to pass them to a procedure that prints the elements.

passing arrays to procedures
#include <stdio.h>

void show(const int n, const int array[])
{
    for (int i = 0; i < n; ++i)
    {
        printf("%d ", array[i]);
    }
    puts("");
}

int main()
{
    int numbers1[] = {2, 7, 4};
    int n = sizeof(numbers1) / sizeof(numbers1[0]);

    show(n, numbers1);

    int numbers2[] = {7, 2, 1, 0, 9};
    int m = sizeof(numbers2) / sizeof(numbers2[0]);

    show(m, numbers2);

    return 0;
}
proc show(arr: openArray[int]) =
  for e in arr:
    stdout.write(e, " ")
  echo ""

let
  numbers1 = [2, 7, 4]
  numbers2 = [7, 2, 1, 0, 9]

show(numbers1)

show(numbers2)

Output in both cases:

2 7 4
7 2 1 0 9

In C, when we pass an array to a procedure, we pass the array and its length (the number of elements) to the procedure. In the procedure we get the number of elemnts and thus we can traverse the array.

In Nim, on the formal parameter list, you can indicate openArray. In this case, you can call the procedure with various arrays whose lengths may be different.

We could write show() in a more complicated way too, but let's keep it simple.

What is an openArray ?

  • openArray is a special parameter type that can accept arrays AND sequences (seq) too, regardless of the size of the array or seq.
  • It's only valid as a parameter type — you can't declare a variable of type openArray.
  • You can use len(), indexing, and iteration on it just like arrays/seqs.

So the following code is completely valid:

proc show(arr: openArray[int]) =
  for e in arr:
    stdout.write(e, " ")
  echo ""

let
  numbers1 = [2, 7, 4]          # static array

  numbers2 = @[7, 2, 1, 0, 9]   # seq, notice the @ sign

show(numbers1)

show(numbers2)

The output is the same as shown above.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 April 08, 20:10