Deutsch   English   Français   Italiano  
<87frmruy1y.fsf@nosuchdomain.example.com>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!news.misty.com!weretis.net!feeder9.news.weretis.net!news.quux.org!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Keith Thompson <Keith.S.Thompson+u@gmail.com>
Newsgroups: comp.lang.c
Subject: Re: C89 "bug"
Date: Fri, 13 Dec 2024 12:29:13 -0800
Organization: None to speak of
Lines: 53
Message-ID: <87frmruy1y.fsf@nosuchdomain.example.com>
References: <vjh8hu$3den0$1@dont-email.me>
	<87jzc3v48r.fsf@nosuchdomain.example.com>
	<vjhu52$3i4tq$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain
Injection-Date: Fri, 13 Dec 2024 21:29:13 +0100 (CET)
Injection-Info: dont-email.me; posting-host="66c77e050ec176338b057ef443530fd1";
	logging-data="3785222"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1/8MCIA9azk+M/Nwq38TMtL"
User-Agent: Gnus/5.13 (Gnus v5.13)
Cancel-Lock: sha1:W8DW2Fd1NkNDFWM7OLQWYfiQdjg=
	sha1:dUi7KsMjZeMsXDnq+c7NNRJca+A=
Bytes: 2789

Thiago Adams <thiago.adams@gmail.com> writes:
> 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.

Yes, that's a good point.  Even in modern C, the initializer for
a static object has to be constant.

A function probably doesn't have much advantage over assigning
the member directly.  Either way, that code has to be executed in
some function.

If this is in human-written code, then there's the risk of forgetting
to invoke the initialization code (or invoking it at the wrong time),
since it can't be directly associated with the object definition.
That's why the C99 and later solution is IMHO much better.)
But if this is generated code, you can just generate code to do
the assignment, perhaps in main().

Initializing u to some known invalid value, if there is one, could
help in detecting the error of forgetting to set a valid value.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */