goto 语句与递归
goto statement vs recursion
我正在编写一个打开文件的函数,其中打开模式取决于用户选择。下面给出的是函数
void open_file(char T)
{
string name;
open:
cout << "\n Enter filename/path : ";
cin >> name;
if(T == 'N')
file.open(name);
else
if(T == 'O')
{
file.open(name, ios::app | ios::in);
if(!file)
{
cout << "\n File not found. Try again";
goto open;
}
file.seekg(0);
}
}
如果没有找到文件,程序会转到open:
,为此我使用了未被识别的goto
语句。请注意 open:
在 name
声明之后开始。
我想知道 goto open
是否比 open_file('O')
内存效率低/慢,因为 open_file('O')
每次调用时都会声明 name
。
请注意:人们给出的不使用 goto
语句的唯一原因是它们使程序更复杂。
如果您使用 while
块而不是 goto
会更容易阅读。不需要递归。
void open_file(char T)
{
string name;
bool retry;
do {
retry = false;
cout << "\n Enter filename/path : ";
cin >> name;
if(T == 'N')
file.open(name);
else
if(T == 'O')
{
file.open(name, ios::app | ios::in);
if(!file)
{
cout << "\n File not found. Try again";
retry = true;
}
else
file.seekg(0);
}
} while (retry);
}
我正在编写一个打开文件的函数,其中打开模式取决于用户选择。下面给出的是函数
void open_file(char T)
{
string name;
open:
cout << "\n Enter filename/path : ";
cin >> name;
if(T == 'N')
file.open(name);
else
if(T == 'O')
{
file.open(name, ios::app | ios::in);
if(!file)
{
cout << "\n File not found. Try again";
goto open;
}
file.seekg(0);
}
}
如果没有找到文件,程序会转到open:
,为此我使用了未被识别的goto
语句。请注意 open:
在 name
声明之后开始。
我想知道 goto open
是否比 open_file('O')
内存效率低/慢,因为 open_file('O')
每次调用时都会声明 name
。
请注意:人们给出的不使用 goto
语句的唯一原因是它们使程序更复杂。
如果您使用 while
块而不是 goto
会更容易阅读。不需要递归。
void open_file(char T)
{
string name;
bool retry;
do {
retry = false;
cout << "\n Enter filename/path : ";
cin >> name;
if(T == 'N')
file.open(name);
else
if(T == 'O')
{
file.open(name, ios::app | ios::in);
if(!file)
{
cout << "\n File not found. Try again";
retry = true;
}
else
file.seekg(0);
}
} while (retry);
}