Floating point values in structs.

Dave P. dave287091 at gmail.com
Fri Dec 18 16:18:12 UTC 2020


I got burned by behavior of struct initialization I didn’t 
anticipate last night.

Consider a struct:

struct Foo {
     float x, y, z;
     int a, b, c;
}

My source C code was initializing it by doing something like:

Foo f = {.y = 3}

Which uses the C behavior that all the other fields will be set 
to 0.

I thought that the D translation would be:

Foo f = {y: 3}

But to my surprise, that leaves x and z “default initialized”, 
which means nan!

I have some large structs that are essentially configuration 
settings for certain subsystems. Is the proper solution to change 
the struct definition to:

struct Foo {
     float x=0, y=0, z=0;
     int a, b, c;
}

to get the behavior I want?

I find the setting floats to nan pretty bizarre. If the compiler 
is going to introduce the overhead of initializing all the 
variables anyway, why set it to nan when integer types get set to 
the useful default of 0? And if it knows that I am not 
initializing my floats, why not tell me?


More information about the Digitalmars-d-learn mailing list