Skip to navigation
   
Dave F's Blog

goto’s in C - a masterclass in coding sneakery

By Dave F in Reader

Posted in Coding on November 23, 2006 at 3:43 pm

Permalink | Author Profile

I had the fundamental rule “you mustn’t use goto’s” well drummed into me in my formative days but I was also programming in BASIC and assembler so I needed them (albeit in a strict structured format). I am therefore neither terrified by or delighted with them but I am still quite shocked to see them in “proper” code. I inherited some ‘C’ code the other day which had a raft of the beggars.

They were quite sensibly used as the structure was:

do_init(){
start initialising
if it failed goto error
do some more
if it failed goto error
do the last bit
if it failed goto error
return OK
error:
display message // just one message, not duplicated in every failure
return ERR
}

There are neat ways to do this in ‘C’. The obvious one is to abstract the initialising into a function

do_init(){
if (my_init()==ERR){
display message // still just one err, “goto” effected by return
return ERR
}
return OK
}

my_init(){
start initialising
if it failed return error
do some more
if it failed return error
do the last bit
if it failed return error
return OK
}

A sneakier way is the pretend switch (or loop)

switch(1){
default:
case 1:                      // using “default” will generate (ignorable) compiler warnings!
start initialising
if it failed break
do some more
if it failed break
do the last bit
if it failed break
return OK
}
display message
return ERR

Basically you’re using break as a goto but because it can only goto one place (ie “}”) it forces structure rather than relying on potentially unsafe goto’s to implement what was basically sound structure anyway.

12345
Not yet rated
Loading ... Loading ...

Previous Post | Next Post

 
 
Comments
This article has no comments yet.

Make a comment

* required

* required

We stop spam using reCaptcha.
Type the words below and click Submit Comment.

Advertisement