Using mixin in array declarations
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Nov 19 05:57:26 PST 2016
On Saturday, November 19, 2016 09:46:08 Marduk via Digitalmars-d-learn
wrote:
> In C one can do the following:
>
> # define N 10
>
> double M[N][N];
>
>
> In D I would like to achieve the same result. I tried with:
>
> mixin("int N = 10;");
>
> double[N][N] M;
>
>
> but the compiler (DMD) complained with Error: variable N cannot
> be read at compile time.
>
> What am I doing wrong?
A string mixin literally puts the code there. So, doing
mixin("int n = 10");
double[n][n] m;
is identical to
int n = 10;
double[n][n] m;
except that you made the compile do the extra work of converting the string
mixin to the code. String mixins really only become valuable when you start
doing string manipulation rather than simply using string literals. If you
want a compile-time constant, then use the enum keyword. e.g.
enum n = 10;
double[n][n] m;
And if you want the value of n to be calculated instead of being fixed, then
you can even do something like
enum n = calcN();
double[n][n] m;
so long as calcN can be run at compile time.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list