Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting undeclared identifier in code copied from a book

Tags:

c++

Well I think the below program is okay but it is giving following error

op: undeclared identifier

I just cant understand why this is happening because it is the same exact code I copied it from "programming principles and practice using c++".

#include "../../std_lib_facilities.h"

using namespace std;

int main()

{
    cout << "Please enter an expression. We can handle +,-,* and /" << "\n";
    cout << "Add an x to end expression" << "\n";

    int lval = 0;
    int rval;

    cin >> lval;
    if (!cin) error("No first operand");
    for (char op; cin >> op;)
        if (op != 'x') cin >> rval;
    if (!cin) error("No second operand");

    switch (op) {

    case'+':
        lval += rval;
        break;

    case'-':
        lval -= rval;
        break;

    case'*':
        lval *= rval;
        break;

    case'/':
        lval /= rval;
        break;

    default:

        cout << "Result: " << lval << '\n';
        keep_window_open();
        return 0;
    }

}
like image 572
Ali Khurram Avatar asked Nov 20 '25 05:11

Ali Khurram


1 Answers

The scope of variables declared in for loops is limited to the for loop. In order to use op outside the for loop you need to change it to

char op;
for (; cin >> op;)

But while we are changing things lets just make this a while loop

char op;
while (cin >> op)

Some compilers allowed using variables declared in a for loop outside the for loop but that is not standard and it should not be relied on. An easy way to tell if you have a non conforming compiler is to run

int main()
{
    for(int i = 0; i < 0; i++) {}
    i++;
}

The i++ should cause an error(example).

like image 143
NathanOliver Avatar answered Nov 21 '25 18:11

NathanOliver