简体   繁体   English

goto 语句与递归

[英]goto statement vs recursion

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.如果未找到该文件,则程序将open: ,为此我使用了不受欢迎的goto语句。 Please note that open: starts after the declaration of name .请注意open: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.我想知道goto open是否比open_file('O')内存效率低/慢,因为open_file('O')每次调用时都会声明name Please note: The only reason people give for not using goto statements is that they make the program more complex.请注意:人们不使用goto语句的唯一原因是它们使程序更加复杂。

It would be easier to read if you would have used a while block instead of goto .如果您使用while块而不是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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM