www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - D Static Array

reply Salih Dincer <salihdb hotmail.com> writes:
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 bounds
One 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
parent Adam D Ruppe <destructionator gmail.com> writes:
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.
 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
This is not supported in D.
Jan 15 2023