Search code examples
c++debugginggoto

Why is my functioning giving me a "expected primary-expression before '}' token" while using a goto?


My function is giving me "expected primary-expression before '}' token" while using a goto and I don't know why.

This code worked as-is in main before I put it into a function.

It works when I replace the 'goto' with 'break', but I need to know why this is.

void fileInputLoop(ifstream& inputFile){
    do{

        cout << "Enter data file name: ";
        getline(cin, fileName);
        previousFileName = fileName;
        // The user will press enter to exit data input 
        if(fileName == ""){
            // If no file name is entered, exit this input loop
            goto skip_data_input_loop;

        }else{
            // Check to see if input is an existing file
            inputFile.open(fileName);
            if(!inputFile.is_open()){
                cout << "File is not available." << endl;
            }else{
                // FILE IS OPEN, DO SOMETHING WITH IT
                ReadData(inputFile);
                inputFile.close();
            }
        }
        // If a second++ file is read in, the previous file will be set accordingly
        // This is to track if a duplicate is from the same file or a new file
        previousFileName = fileName;

    }while(true);
    skip_data_input_loop:
}

Solution

  • The problem is that labels are to label a statement. In other words, you can't have a label without a statement following.

    With the caveat of my comment, you could solve it by having an empty "null" statement after the label:

    skip_data_input_loop: /* Empty statement using the semicolon */ ;