digitalmars.D.learn - D Static Array
- Salih Dincer (35/42) Jan 15 2023 I wonder why the above code is allowed in D? Is there a special
- Adam D Ruppe (7/11) Jan 15 2023 The = 40 means fill all array entries with the number 40.
I wonder why the above code is allowed in D? Is there a special reason for this? ```d import std.stdio : writeln; void main() { int[0] arr = 40; // ? typeid(arr).writeln(": ", arr); // int[0]: [] } ``` When we look at the C side, the situation is deplorable! But I can claim that there is only one element allowed there. I found the following comment of unknown origin:In C99 and later C standards, an array size can be defined as 0 and it can include a feature called flexible array member (FAM) which is an array member without specifying its size, it means the size of array will be determined at runtime. However, FAM can only be used in struct and union types and must be the last member of the struct/union.I tried more than claimed: ```c #include <stdio.h> int main() { int arr[0]; arr[0] = 40; arr[1] = 41; arr[2] = 42; for (int i = 0; i < 3; i++) { printf("%d ", arr[i]); } return 0; // "40 880975872 787869145" } ``` And yeah, going out of range is not allowed on D, getting this error:array index 0 is out of boundsOne more question: Since 0 element initialize is allowed in D, so where did 40 go? I can see that number 40 in C! Thanks... SDB 79
Jan 15 2023
On Sunday, 15 January 2023 at 14:23:59 UTC, Salih Dincer wrote:int[0] arr = 40; // ?The = 40 means fill all array entries with the number 40. The [0] means there are no array elements. So it filled all the 0 elements with the number 40. If it was like int[3] arr = 40, then arr[0], arr[1], and arr[2] would all be 40.This is not supported in D.In C99 and later C standards, an array size can be defined as 0 and it can include a feature called flexible array member (FAM) which is an array member without specifying its size
Jan 15 2023