Does C allow the use of a struct type for itself?

So we have a structure type like this:

typedef struct
{
    U64 low;
    U64 high; 
} U128;

      

Then somewhere in the code, as a result of the expansion of the macro, there is such an assignment:

*ptr = (U128)value;

      

Where ptr

it matters U128*

. And this throws the following error:

error C2440: 'type cast' : cannot convert from 'U128' to 'U128'

      

The question arises: are such suicides allowed in C? Did I just notice a compiler error?

Additional question:

This is a generalized macro that allows 8, 16, 32, 64, 128, etc. as arguments and other typedefd types as numbers and work without issue: is there any workaround? I would like to avoid memcpy for performance reasons.

+3


source to share


1 answer


Not.

Standard text (draft C11) requiring this behavior is given in 6.5.4.2:

If the type name does not indicate a void type, the type name must indicate an atomic, qualified, or unqualified scalar type, and the operand must be a scalar type

In other words, you cannot use struct

at all.



One fix could, of course, be to remove the right side or make a beaten copy:

memcpy(ptr, &value, sizeof *ptr);

      

Perhaps this will be optimized as the copied size is quite small. Note that this sizeof *ptr

is a safer choice, and sizeof value

may overflow if the input value

is of an unexpected type.

+4


source







All Articles