Hello.
Can Nim fill array with same value (not zero) while defining array? I know about fill method in standard library, but it is initialization in runtime (instead of creating static filled memory blocks in pre pre main by compiler).
int array[10] = {500};
int main() {
printf("%d", array[0]);
return 0;
}
Not sure if there is a better/easier way, but this will only fill the array at compile time:
template initArray[T](size: static int, value: T): untyped =
block:
var res: array[size, T]
for i in 0 ..< res.len:
res[i] = value
res
const arr = initArray[int](10, 500)
const arr2 = initArray[string](5, "hey")
proc main() =
echo arr
echo arr2
main()
For clarity this does not require a template, a procedure works fine:
proc initArray[T](size: static int, value: T): array[size, T] =
for ele in result.mitems:
ele = value
const arr = initArray(10, 500)
const arr2 = initArray(5, "hey")
proc main() =
echo arr
echo arr2
main()
By the way, the C code you provided doesn't actually fill the array with 500; it sets the first element to 500 and fills the rest with zeroes.
Thanks to all for examples. I thought that it is can be done only with generating array/sequence during compile time.
@xigoi Sorry, it's my error, you are right. Non zero fill initialization in C really possible only in runtime. Or I must use GCC extension or doing filling sequence with preprocessor.