Reputation: 211
I am working on a language where there is not any goto
,jump
function. For example, Matlab.
Can you please help me on how to avoid using it? Is there any simple trick solving my problem?
Upvotes: 0
Views: 2377
Reputation: 5813
As @Andrey mention you can use if
or if-else
statement. In many cases loops like while
, for
is one-to-one replacements to the if-else
and goto
.
You should also consider to use break
and continue
statement as @Oli said above.
In some rare cases you can use exception (I don't know whether the Matlab supports it) in order to "go back". This is somewhat controversial, but maybe in your case it will fit.
redothat:
foobar()
...
And inside foobar() in some place you have
if cond
goto redothat;
end
you can do:
while(true){
try {
foobar();
...
break;
}
catch(YourApplicationException e){
//do nothing, continiue looping
}
}
And inside foobar() in some place you have
if cond
throw YourApplicationException();
end
Or you can do something like this:
you can do:
boolean isOk = false;
while(! isOk){
try {
foobar();
...
isOk=true;
}
catch(YourApplicationException e){
//do nothing, continiue looping
}
}
Upvotes: 1
Reputation: 16045
You should consider using break
and continue
Instead of:
for ...
...
if ...
goto nextstuff:
end
end
nextstuff:
You can do:
for ...
...
if ...
break
end
end
And as @andrey said, you can often replace goto
by if-else
Instead of doing:
if cond
goto label
end
...
foobar()
...
label:
foobar2()
you can do:
if ~cond
...
foobar()
...
end
foobar2()
When you use a goto to go back, you can replace it by a while:
Instead of doing:
redothat:
foobar()
...
if cond
goto redothat;
end
you can do:
while cond
foobar()
...
end
Upvotes: 3
Reputation: 20915
Well, first of all you might as well ask it without the matlab tag, you might get better answers. That is because this kind of question is common to almost all of the modern languages.
Instead of goto
and jump
you should use either conditionals like if
,if-else
or loops like while
,for
, depending on what you want to achieve.
Check out GOTO still considered harmful?, Why is goto poor practise?.
Upvotes: 1