Confusion/trying to understand CTFE keywords

Steven Schveighoffer schveiguy at yahoo.com
Tue Jun 5 18:00:05 UTC 2018


On 6/5/18 12:10 PM, Stefan Koch wrote:
> 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.

No, it's definitely a bug. main is not being evaluated at compile time. 
The real result of this function should be a compile-time error -- 
__ctfe is a *runtime* value that is always defined based on whether you 
are __ctfe or not. Therefore, n must be a runtime value, and not usable 
as a static array dimension.

If the posted code is valid, then this should be valid as well:

static if(__ctfe)
    immutable n = 1;
else
    immutable n = 2;

But it's not.

-Steve


More information about the Digitalmars-d-learn mailing list