C++ - Is Goto a Good Practice?

Started by
45 comments, last by SiCrane 11 years, 5 months ago
A small remark - the guys who dislike goto are on the forums whining about it while the guys who like goto are actually coding something.

Which do you want to be?

(EDIT: Another small remark - guys around here seem to have no clue about the concept of humour!)
Advertisement

... the guys who dislike goto are on the forums whining about it while the guys who like goto are actually coding something.
[/quote]
Wow. That is an impressively simplistic false dichotomy.
... or a bad joke :) And though I (seriously) don't think goto is bad by default, I've never had a reason to use it.
I think one of the only times I ever used goto was to get out of a three-level nested loop. It wasn't final code and I couldn't be bothered to add break flags or put the loops in their own function, so I just used goto as an extended break. But I wouldn't recommend it - it's not really compatible with higher level control flow, but it's nice to know it exists.

I'm sure there are instances out there where goto may in fact be beneficial (someone mentioned cleaning up C functions, which is a good one, of course you can achieve the same goal by carefully nesting your allocations but sometimes goto is the only elegant way to do it), but you certainly don't use goto "just because you can".

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”

Say no to goto!~~

heehee.
I don't actually know what happens in the following scenarios. Does goto respect rules of the scoped objects?

{
std::string tee("hee");
goto forward;
}
forward:
// what happens with destruction of tee? Memory leak I guess.
backward:
// what happens with destruction of tee? Memory leak I guess.
int i = 0;
if (i == 0)
{
i = 1;
std::string tee("hee");
goto backward;
}
if (rand()%2 == 0)
goto forward2;

{
std::string tee("hee");
forward2:
// tee isn't constructed here with goto. Crash if referenced I guess.
// tee must be destructed at scope exit if entered without goto.
}


Does goto break all RAII objects?
A goto out of a block destroys all objects that have been initialized in that block. A goto into a block after a statement creating an object with an initializer is ill-formed (i.e. the compiler should bitch at you for trying it). So in your specific scenario, the first goto to forward should properly destroy tee. The goto to backward will destroy the second tee because control flow still leaves that block. The goto to forward2 should trigger a compiler error.

This topic is closed to new replies.

Advertisement