goto和jump命令的替代品

时间:2012-01-24 16:19:44

标签: language-agnostic goto

我正在开发一种没有gotojump功能的语言。例如,Matlab。 你能帮我解决一下如何避免使用它吗?有没有解决我问题的简单技巧?

3 个答案:

答案 0 :(得分:3)

您应该考虑使用breakcontinue

而不是:

for ...
   ...
   if ...
      goto nextstuff:
   end
end
nextstuff:

你可以这样做:

for ...
   ...
   if ...
      break
   end
end

正如@andrey所说,您通常可以将goto替换为if-else

而不是:

if cond
  goto label
end
...
foobar()
...
label:
foobar2()

你可以这样做:

if ~cond
  ...
  foobar()
  ...
end
foobar2()

使用goto返回时,可以暂时替换它:

而不是:

redothat:
foobar()
...
if cond
   goto redothat;
end

你可以这样做:

while cond
  foobar()
  ...
end

答案 1 :(得分:1)

嗯,首先你可以问没有 标签,你可能会得到更好的答案。这是因为这种问题在几乎所有现代语言中都很常见。

您应使用gotojump等条件或ifif-else等循环,而不是whilefor。你想要实现的目标。

结帐GOTO still considered harmful?Why is goto poor practise?

答案 2 :(得分:1)

正如@Andrey提到的,您可以使用ifif-else声明。在许多情况下,whilefor等循环是if-elsegoto的一对一替代。

您还应考虑使用breakcontinue声明,如上所述@Oli。

在极少数情况下,您可以使用异常(我不知道Matlab是否支持它)以“返回”。这有点争议,但也许在你的情况下它会适合。

redothat:
foobar()
...

在某个地方的foobar()里面你有

if cond
   goto redothat;
end

你可以这样做:

while(true){
 try {
   foobar();
   ...
   break;
 }
 catch(YourApplicationException e){
   //do nothing, continiue looping
 }  
}

在某个地方的foobar()里面你有

if cond
  throw YourApplicationException();
end

或者你可以这样做:

你可以这样做:

boolean isOk = false;   
while(! isOk){
 try {
   foobar();
   ...
   isOk=true;
 }
 catch(YourApplicationException e){
   //do nothing, continiue looping
 }  
}