How bad is the goto statement really, and why?
It's really bad for all the normal reasons given. It's prefectly fine when emulating labeled loops in languages that don't support them.
Replacing it with functions will in many cases scatter logic that really should be read as the same unit. This makes it harder to read.
Nobody likes to follow a trail of functions that don't really do anything until at the end of the journey, when you have somewhat forgotten
where you started from.
Replacing it with booleans and a bunch of additional ifs and breaks is just really clunky and makes it harder to follow real intentions, like any noise.
In java (and javascript), this is perfectly acceptable (labeled loops):
outer: while( true ) {
for( int i = 0; i < 15; ++i ) {
break outer;
}
}
In C#, it looks like the very close equivalent isn't:
while( true ) {
for (int I = 0; I < 15; I++) {
goto outer;
}
}
outer:;
Because of the word goto
, which has a psychological effect of making people drop all their common sense and make them link xkcd regardless of context.
Is there a more effective way to break the main loop than using the 'goto' statement?
In some cases there isn't, which is why the other languages provide labeled loops and C# provides goto
. Note that your example is too simple and it makes
the work-arounds not look too bad because they're tailored to the example. In fact, I could just as well suggest this:
for (int I = 0; I < 15; I++) {
break;
}
How about this:
int len = 256;
int val = 65536;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
if (i + j >= 2 * val)
{
goto outer;
}
val = val / 2;
}
}
outer:;
Does this still look good to you:
int len = 256;
int val = 65536;
for (int i = 0; i < len; i++)
{
if (!Inner(i, ref val, len))
{
break;
}
}
private bool Inner(int i, ref int val, int len)
{
for (int j = 0; j < len; j++)
{
if (i + j >= 2 * val)
{
return false;
}
val = val / 2;
}
return true;
}
while(true)
rather thando while(true)
? – MarilynIs there a more effective way to break the main loop than using the 'goto' statement?
How is this not a legitimate question? – CarnayInner
function without the parent loop for example. – Convince