如何使用"goto"语句来摆脱循环
for(i = 0; (i < 9); i++)
{
for(j = 0; j < 9; j++)
{
//cout << " " << Matrix[i][j];
//cout << "i: " << i << endl;
if(Matrix[i][j] == 0)
{
//temp = 10;
[goto] ;
//break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想保留i和j离开嵌套for循环时的值.我怎样才能使用goto语句呢?
das*_*ght 11
像这样:
int i,j;
for(i = 0; i < 9; i++)
{
for(j = 0; j < 9; j++)
{
//cout << " " << Matrix[i][j];
//cout << "i: " << i << endl;
if(Matrix[i][j] == 0)
{
//temp = 10;
goto end;
//break;
}
}
}
end:
cout << i << " " << j << endl;
Run Code Online (Sandbox Code Playgroud)
就像你goto在任何其他情况下使用一样.只要你没有将范围与其中的局部变量交叉,你实际上可以将其视为"转到此行和那行":
for (/* ... */) {
/* ... */
if (/* ... */)
goto finalise;
}
finalise:
foo = bar; //...
Run Code Online (Sandbox Code Playgroud)
但是,有很多情况goto是指示代码设计不完善的指标.决不是总是,而是经常.
我建议你使用gotos大哥return并将你的代码分解为函数:
inline std::pair<int,int> findZeroEntry(std::vector matrix) {
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
if (Matrix[i][j] == 0)
return std::make_pair(i,j);
return std::make_pair(9,9); // error
}
Run Code Online (Sandbox Code Playgroud)