Casting between structs of the same size is treated as a bit cast?

Dave P. dave287091 at
Wed Oct 20 04:14:37 UTC 2021

I am confused on how casting structs works. According to point 9 

> Casting a value v to a struct S, when value is not a struct of 
> the same type, is equivalent to:
> ```d
> S(v)
> ```

However, the following program compiles and the resulting 
execution indicates the bits are just being reinterpreted.

// casttest.d
import std;

struct Foo {
     int i;
     float x;

struct Bar {
     float i;
     int x;

void main(){
     Foo foo = Foo(10, 1.035);
     auto b = cast(Bar)foo;
     auto c = cast(Bar)b;
     // auto d = Bar(foo); // casttest.d(21): Error: cannot 
implicitly convert expression `foo` of type `Foo` to `float`
     // auto e = Bar(b); // casttest.d(22): Error: cannot 
implicitly convert expression `b` of type `Bar` to `float`

Execution results in:

Foo(10, 1.035)
Bar(1.4013e-44, 1065646817)
Bar(1.4013e-44, 1065646817)

Additionally, the commented out lines indicate that what the spec 
claims the cast is equivalent to wouldn’t even work.

Is this a bug in my understanding? Bug in the spec? Bug in the 

More information about the Digitalmars-d-learn mailing list