Confusion/trying to understand CTFE keywords

Gopan gggopan at gmail.com
Tue Jun 5 09:36:22 UTC 2018


On Sunday, 3 June 2018 at 21:32:06 UTC, gdelazzari wrote:
> Couldn't a keyword like "ctfe" (just making it up right now) 
> exist? So that, when seeing something like
>
> ctfe myNumber = 5;
>
> ctfe if (myNumber + 2 == 7)
> {
>   // ...
> }
>
> one could immediately understand that the code is 
> executed/evaluated at compile time. True, after someone knows 
> that "static" and "enum" mean (in the above example) that some 
> compile-time things are happening, it's fine. I just find it a 
> bit confusing not having a dedicated keyword but re-using 
> existing ones that also serve other purposes...
>

Hi gdelazzari,

While seeing your post, I just recollected my post 4 years ago. 
https://forum.dlang.org/post/wbfnvwulchrpnrxovqbr@forum.dlang.org
I recommend you to go through it.  Let me put here my thoughts 
again.

void main()
{
     immutable n = __ctfe ? 1 : 2;
     int[n] a;
     assert(a.length == n); // fails, wat
}

Here, the declaration int[n] a forces n to be calculated during 
compile time.  During compile time, __ctfe is true (I dont know 
if it a variable or macro, etc).  Hence the value of n during 
compile time is 1.  So, size of the array a is 1.  Anyway, n is 
calculated during runtime too. At runtime, __ctfe is false.  n 
becomes 2.  Finally, at runtime a.length is 1 and n is 2.

This shocked me.  ie While reading a huge code, you need to check 
how you got the value of n, which I personally dont want to.

While this scared me away, I thought about it.  What is the 
underlying problem?  My immediate answer is that the same 
variable getting computed during both compile time and runtime 
caused this issue.  Why should a variable get a new value at 
runtime if it has already got a value during compile time, for 
the same statement?

May be I am less imaginative.  I still wish some could enlighten 
me to accept this behavior if everybody else thinks it is right.

Regards,
Gopan


More information about the Digitalmars-d-learn mailing list