Confusion/trying to understand CTFE keywords

Stefan Koch uplink.coder at googlemail.com
Tue Jun 5 16:10:02 UTC 2018


On Tuesday, 5 June 2018 at 13:27:35 UTC, Steven Schveighoffer 
wrote:
> On 6/5/18 6:40 AM, Simen Kjærås wrote:
>> On Tuesday, 5 June 2018 at 09:36:22 UTC, Gopan wrote:
>>> void main()
>>> {
>>>     immutable n = __ctfe ? 1 : 2;
>>>     int[n] a;
>>>     assert(a.length == n); // fails, wat
>>> }
>> 
>> That's gotta be a bug - that should give a 'variable n cannot 
>> be read at compile time' error. The fact that n is immutable 
>> shouldn't be enough to use it at compile time. Filed as 
>> https://issues.dlang.org/show_bug.cgi?id=18945.
>
> Indeed it is a bug. Interesting to see what the compiler sees 
> as its AST:
>
> import object;
> void main()
> {
>         immutable immutable(int) n = __ctfe ? 1 : 2;
>         int[1] a = 0;
>         assert(1LU == cast(ulong)n);
>         return 0;
> }
>
> This is what -vcg-ast spits out.
>
> Note the int[1].
>
> -Steve
This is not bug just not very intuitive.

Since you are declaring a static array the value of n needs to 
known at compiletime.
so it'll  try to evaluate n at an compile-time context in which n 
is 1.
however when code-generation for the function is done __ctfe will 
be false.
Causing the n variable to be initialized to 2.

Therefore n will not be equal to a.length.


More information about the Digitalmars-d-learn mailing list