Thread overview
static-if cant compile
Jul 19, 2015
Clayton
Jul 19, 2015
Rikki Cattermole
Jul 19, 2015
Adam D. Ruppe
July 19, 2015
Pardon me for trivial question, Am new to D.


Why would a statement as below fail to compile. The plan is to do some computation at compile-time hence considering the static-if statement which fails to compile. The regular  if-statement compiles but is not useful since it is a runtime construct.

The error message I get is :  Error: variable i cannot be read at compile time




foreach( i; 0..size-1){
		static if  ( i == -1 ){
			//Do something
		}

	}
July 19, 2015
On 20/07/2015 12:17 a.m., Clayton wrote:
> Pardon me for trivial question, Am new to D.
>
>
> Why would a statement as below fail to compile. The plan is to do some
> computation at compile-time hence considering the static-if statement
> which fails to compile. The regular  if-statement compiles but is not
> useful since it is a runtime construct.
>
> The error message I get is :  Error: variable i cannot be read at
> compile time
>
>
>
>
> foreach( i; 0..size-1){
>          static if  ( i == -1 ){
>              //Do something
>          }
>
>      }

static if is for compile time known constants.
if is for runtime variables.

In this case it would be a runtime variable even if it is known at compile time.
Known at compile time != run at compile time. They overlap yes, just not the same thing.
July 19, 2015
On Sunday, 19 July 2015 at 12:17:04 UTC, Clayton wrote:
> Pardon me for trivial question, Am new to D.

In D, you can run regular runtime code at compile time in a lot of cases. Just write an ordinary function that returns the data you need, then use it in a static variable initialization.

// example function, notice regular if and variables inside
int calculate(int i) { if(i < 0) return -i; else return i; }


static int value = calculate(5); // this is run at compile time



Ordinary functions will be interpreted if asked for their result in a context that only can be run at compile time, like a static variable initialization or inside a static if.