C99: cast double to struct?
In the huge (millons of LOC) C project I want to expand a "double" type into a struct containing two doubles:
Now I have
typedef double popular_type;
//... a lot (>1k) usage of the type in expressions like:
popular_type a;
a = (popular_type) some_double_variable;
I want to change popular_type definition into
#ifdef SYNTHETIC_POPULAR_TYPE
typedef struct {
double orig_field;
double additional_field;
} popular_type;
#else
typedef double popular_type;
#endif
If I do not change the expressions like
popular开发者_如何学Python_type a;
a = (popular_type) some_double_variable;
to
popular_type a;
a.orig_field = some_double_variable;
will the program work?
How can I redeclare popular_type
in order that I do not have to change all assignments?
Unfortunately, it's not possible.
If you change popular_type
definition to
typedef struct {
double orig_fiels;
double additional_field;
} popular_type;
without changing assignments, the compiler will throw the error conversion to non-scalar type requested
, so your code won't even compile, and there is no workaround over this. The only superior scalar type above double
is __float128
, and you can't just use the extra bytes to store your fields.
You really have to change the assignments, unfortunately.
You'll need to change the code -- but first, you'll need to decided exactly what you want the code to do.
The result of converting a double
to the version of popular_type
that's typedef'ed as a double
is well defined. After all, they're really the same type. But what is the result of converting a double
to a structure? Given a double
with the value 1.25, what should be the values of orig_field
and additional_field
in the resulting structure?
Once you've decided on the semantics, you can write a function (possibly inline) or perhaps a macro that does the conversion for you. You'll still need to change each conversion so it calls your new function or macro (and possibly some assignments without casts, since with the current definition a cast is not required, as @Sam Hoice points out). Fortunately, the compiler will tell you where this needs to be done.
精彩评论