-3
#include <iostream>
using namespace std;

void menue()
{

    cout<<"Choose an option"<<endl;
    cout<<"========================"<<endl;
    cout<<"1.  Open"<<endl;
    cout<<"1.  Close"<<endl;
    cout<<"1.  Exit"<<endl;

}

void menueOptions()
{

    do
    {
        int input;
        cout<<"Enter selection here:  "<<flush;
        cin >> input;

        switch(input)
        {

        case 1:
            cout<<"Opening..."<<endl;
            break;
        case 2:
            cout<<"Closing..."<<endl;
            break;
        case 3:
            cout<<"Exiting..."<<endl;
            break;
        default:
            cout<<"Invalid input"<<endl;

        }
    }
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}

int main()
{

    menue();
    menueOptions();


return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Coaly boi
  • 21
  • 1

1 Answers1

2

The variable input is declared within the block scope (compound statement) of the do-while statement.

    do
    {
        int input;
        //...
    }
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}

So it may not be used outside the scope in the condition of the do-while statement.

(Note: even if a do-while statement does not use a compound statement it has its own block scope between do and while. From the C++17 Standard (8.5 Iteration statements)

2 The substatement in an iteration-statement implicitly defines a block scope (6.3) which is entered and exited each time through the loop. If the substatement in an iteration-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original statement.

--end note)

Declare it before the do-while statement

    int input;
    do
    {
        //...
    }
while(input < 1 || input > 3); // ERROR HERE (INPUT WAS NOT DECLARED IN THIS // SCOPE)
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335