Re: Goto still considered ful
Richard Bos wrote:
> Peter Pichler <usenet@pichler.co.uk> wrote:
>>Ed Jensen wrote:
>>
>>>done:
>>> if (sf)
>>> fclose(sf);
>>> if (df)
>>> fclose(df);
<big snip>
>>In addition, [this style] requires [all variables] initialised to "harmless" values
>>which can hide bugs later on.
>
> No, it doesn't. For example, in the code from which the above is quoted,
> the initialisations of sf and df are unnecessary: fopen() will always
> return either a valid FILE *, or a null pointer, never garbage.
The context was lost in snipping. It went something like this:
type1 var1;
type2 var2; /* you need, "= safe_value;" here */
initialize(var1); /* what if this fails? */
if (wrong(var1))
goto end;
initialize(var2);
if (wrong(var2))
goto end;
do_something(var1, var2);
end:
if (need_deinitialize(var1))
deinitialize(var1);
if (need_deinitialize(var2)) /* BANG! (maybe) */
deinitialize(var2);
Now, if initializing var1 fails, var2 remains unitialized and your
cleanup section is a potential trouble. Therefore you need to initialize
var2. With more than two variables, you need to initialize all of them
before jumping to end.
Declaring variables as local as possible avoids this problem.
(I am not fighting a holy war, only explaining.)
|