Reputation: 19431
So we have a struct type like this:
typedef struct
{
U64 low;
U64 high;
} U128;
Then somewhere in the code as a result of macro expansion there is an assignment like this:
*ptr = (U128)value;
Where ptr
is of U128*
. And this causes the following error:
error C2440: 'type cast' : cannot convert from 'U128' to 'U128'
The question is: Are such self casts allowed in C? Am I just spotted a compiler bug?
Additional question:
This is a generalized macro that allows 8, 16, 32, 64, 128, etc. as arguments, and other types are typedefd as numbers and work without problems: are there any workaround? I would like to avoid memcpy for performance reasons.
Upvotes: 3
Views: 303
Reputation: 399803
No.
The (draft C11) standard text that requires this behavior is in §6.5.4.2:
Unless the type name specifies a void type, the type name shall specify atomic, qualified, or unqualified scalar type, and the operand shall have scalar type
In other words, you can't cast struct
s at all.
One fix could of course be to remove the right-hand side cast, or do a bitwise copy:
memcpy(ptr, &value, sizeof *ptr);
This will perhaps be optimized away, since the size being copied is quite small. Note that sizeof *ptr
is a safer choice, using sizeof value
would risk overflowing if the incoming value
has an unexpected type.
Upvotes: 5