diff --git a/Nimrod-for-C-programmers.md b/Nimrod-for-C-programmers.md index fc2b65c..e165127 100644 --- a/Nimrod-for-C-programmers.md +++ b/Nimrod-for-C-programmers.md @@ -22,6 +22,42 @@ http://nimrod-lang.org/manual.html Operator OverloadingNo (Yes w/ C++)Yes Custom OperatorsNoYes + +### Arrays + +In C an array is more or less syntactic sugar for pointers. In Nimrod, arrays are much more strict and safe to use. They are pass-by-value (meaning they're copied at assignment). When passing an array to a proc in Nimrod, the argument is a read-only reference, meaning it can't be assigned to. Take the following example: + +**C:** +```C +void foobar(int z[4]) { + z[5] = 5; + printf("%d\n",z[5]); +} +int main() { + int x[4] = {1, 2, 3, 4}; + foobar(x); + printf("%d\n", x[1]); + return 0; +} +``` + +**Nimrod:** +```Nimrod +proc foobar(z: array[0..3, int]) = + z[5] = 5 # Error: Cannot assign to z + echo z[5] # Error: Index out of bounds. + +var x = [1, 2, 3, 4] + +foobar(x) +``` + +The C-code will compile, it may or may not crash. The Nimrod code will not compile. If you mean to change the array that was passed to the procedure, you can change the the signature of the procedure to ```proc foobar(z: var array[0..3, int])```. Now you will only get index out of bounds error. If you change the index in both lines to 1, the code will compile. If the index is a variable, Nimrod will include run-time checks on the bounds of the array. + +In C, you can pass an ``int[3]`` to the foobar function, and the compiler will not complain. In this case Nimrod would not compile. You can use an openarray to accept an array of any size, and you can use low(z) and high(z) to query the bounds of the array. + +Nimrod arrays can also be indexed from any number. That is, ``z: array[1..4, int]`` is an array of int indexed from 1 to 4. Trying to access ``z[0]`` would throw an index out bounds error. + ### Structs - Tuples and Objects Tuples and Objects in Nimrod are kind of like structs in C, but not really.