Sujet : Re: C89 "bug"
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 13. Dec 2024, 19:51:43
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vjhvnv$3igdc$1@dont-email.me>
References : 1 2 3
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 13/12/2024 19:24, Thiago Adams wrote:
Em 12/13/2024 3:15 PM, Keith Thompson escreveu:
Thiago Adams <thiago.adams@gmail.com> writes:
Does anyone knows how can I convert this code (external declaration) to C89?
>
union U {
int i;
double d;
};
>
union U u = {.d=1.2};
>
The problem is that in C89 only the first member of the union is
initialized.
>
The obvious solution is:
union U u;
u.d = 1.2;
But that works only if u has automatic storage duration.
>
You could also define a function that takes a double argument and
returns a union U result.
Like this?
union U {
int i;
double d;
};
union U f(){ union U u; u.d = 1.2; return u;}
union U u = f();
The problem is that f() is not a constant expression for external declarations.
Can you use gcc extensions here, or are you looking for strict C89 compliance?
(To me, the "bug" is using C89 in the first place, but you have your reasons for that.)
Another option if you are generating code is to make your union :
union U {
struct { unsigned int lo; unsigned int hi; } raw;
int i;
double d;
};
and always initialise it with the underlying representation for the values and types that you want. (I believe you are generating the code, so that should be practical even for floating point data.)
However, that puts a dependency on the endianness and size of types.