goto’s in C - a masterclass in coding sneakery
Posted in Coding on November 23, 2006 at 3:43 pm
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.
Make a comment
Tag cloud
Archives
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
Most commented posts
Highest Rated Blog Posts
- No excuse - it's free to encrypt! (100%)
- PC Advance Required (100%)
- Virtualization's Dark Side - or stating the obvious for beginners (100%)
- Tabs - I might change my mind? (100%)
- Which Linux do you drink? (100%)
- Sat Nag (100%)
- What has you tube ever done for us? (100%)
- Is your back door open? (90%)
- What they don't say... (90%)
- Measuring the Metrics (80%)

