I am writing a function that opens a file, where open mode depends upon user choice. Given below is the function
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);
}
}
if the file is not found, the program goes to open:
, for that I have used the unappreciated goto
statement. Please note that open:
starts after the declaration of name
.
I want to know if goto open
is less memory efficient / slower than open_file('O')
or not, since open_file('O')
will declare name
every time it is called.
Please note: The only reason people give for not using goto
statements is that they make the program more complex.
It would be easier to read if you would have used a while
block instead of goto
. No need for recursion.
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);
}