Re: What do you think about the code?



On 2006-07-01, Richard Heathfield <invalid@xxxxxxxxxxxxxxx> wrote:
Andrew Poelstra said:

<snip>

What is easier to read:
/* Start */

while (test[0])
while (test[1])
while (test[2])
{
if (test[3])
goto outOfLoop;
}

outOfLoop:
puts ("Escaped from loop.");

Now add sixty to a hundred lines of actual code, ten lines of comments, and
a couple of years of maintenance, and /then/ ask me whether this is easy to
read.

Or, without goto:

Unstructured version snipped. The break keyword is just goto in a false
moustache.

In practice, status objects are cheap and readable. If they are becoming
unreadable, it's a sign that your function is too big. One huge advantage
of a modular design with strict avoidance of goto, non-documentary
continue, and switchless break, is that it is really easy to refactor a
function that has outgrown its readability. Just chop out the innermost
loop, dump it into a new function, and that's typically almost all that you
have to do. When the control flow is hopping all over the place like a frog
on his wedding night, code simplification is far more difficult to achieve.


Since as a maintenance programmer you've probably had to deal with a lot of
similar code, suppose you were writing a parser and you did this:

c = get_input();

if (we_are_in_a_quote && c != '\"')
goto skip_parsing;

switch (c)
{
/* Parsing code here */
}

skip_parsing:
/* Return parsed text to callee. */


Would that be an appropriate use of goto? Otherwise I've found that I end up
with if statements around most every single case block. (I can't do it around
the whole switch because I don't care if I'm in quotes when checking for the
quote character and the escape character).

--
Andrew Poelstra <http://www.wpsoftware.net/blog>
To email me, use "apoelstra" at the above address.
"You people hate mathematics." -- James Harris
.



Relevant Pages

  • Re: While(1) or for(;;) for infinite loops?
    ... would imply having to escape from it using break, return, goto or exit() instead. ... You can have only one infinite loop in a program. ... A break/ goto is better than messing about with a flag which is introduced purely to avoid having a jump. ...
    (comp.lang.c)
  • [PATCH 1/4] Char: rio, fix cirrus defines
    ... switch ) { ... "command blk %p\n", SubCmd.Addr, CmdBlkP); ... ** If the port is set to store or lock the parameters, ... goto close_end; ...
    (Linux-Kernel)
  • Re: function pointers
    ... The simple goto. ... fixed target label. ... The computed goto, aka switch, select, or caseof, depending ... In C it is the switch. ...
    (comp.lang.c)
  • [PATCH 15/15] audit: validate comparison operations, store them in sane form
    ... err = -EINVAL; ... goto exit_free; ... switch { ...
    (Linux-Kernel)
  • Re: TCL vs. Perl
    ... I don't understand why Perl doesn't have a 'switch' ... goto END; ... A 'C' switch/case statement is something different. ...
    (comp.lang.perl.misc)