www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Conditional compilation of array of structs initializer

reply Tony <tonytdominguez aol.com> writes:
Doing a port of some C code that has an #ifdef in the middle of 
an initialization for an array of structs. I am getting a compile 
error trying to get equivalent behavior with "static if" or 
"version". Is there a way to achieve this other than making two 
separate array initialization sections?

struct a {
    int y;
    int z;
}

immutable string situation = "abc";

int main()
{
    a[] theArray = [
       { 10, 20 },
// version(abc)
static if (situation == "abc")
{
       { 30, 40 },
}
       { 50, 60 }
       ];
    return 0;
}
Nov 09 2017
parent reply Michael V. Franklin <slavo5150 yahoo.com> writes:
On Friday, 10 November 2017 at 06:22:51 UTC, Tony wrote:
 Doing a port of some C code that has an #ifdef in the middle of 
 an initialization for an array of structs. I am getting a 
 compile error trying to get equivalent behavior with "static 
 if" or "version". Is there a way to achieve this other than 
 making two separate array initialization sections?

 struct a {
    int y;
    int z;
 }

 immutable string situation = "abc";

 int main()
 {
    a[] theArray = [
       { 10, 20 },
 // version(abc)
 static if (situation == "abc")
 {
       { 30, 40 },
 }
       { 50, 60 }
       ];
    return 0;
 }
Here's my attempt. There's probably a more elegant way, but it's the best I could do. import std.stdio; struct a { int y; int z; } enum situation = "abc"; int main() { enum head = "a[] theArray = [ {10, 20},"; static if (situation == "abc") { enum middle = "{ 30, 40},"; } else { enum middle = ""; } enum tail = "{ 50, 60 }];"; mixin(head ~ middle ~ tail); writeln(head ~ middle ~ tail); return 0; } The use of enums for this is called manifest constants (https://dlang.org/spec/enum.html#manifest_constants). It's more analogous to #define in C. Mixins are documented here (https://dlang.org/spec/statement.html#mixin-statement) Mike
Nov 09 2017
parent Tony <tonytdominguez aol.com> writes:
Thanks Mike!
Nov 09 2017