mardi 28 mars 2017

Not getting same results using switch statement and if else

I have the following code that looks like this:

if ((peek() >= '0' && peek() <= '9') || peek() == '.'){
        return number();
    }else if (peek() == '('){
        cout<<"(\n";
        get(); // '('
        double result = expression();
        cout<<")\n";
        get(); // ')'
        return result;
    }
    else if (peek() == '-'){
        get();
    }
    return 0;

If I enter something that looks like (2*5) + 7 the output will look like:

(
*
+
)
17

which is the format I want. I want to try to achieve the same results using a switch statement but I can't get it to work with parenthesis. Here is my switch statement:

switch (peek()){
        case '0':
            return number();
            //break;
        case '1':
            return number();
            //break;
        case '2':
            return number();
            //break;
        case '3':
            return number();
            //break;
        case '4':
            return number();
            //break;
        case '5':
            return number();
            //break;
        case '6':
            return number();
            //break;
        case '7':
            return number();
            //break;
        case '8':
            return number();
            //break;
        case '9':
            return number();
            //break;
        case '.':
            return number();
            //break;
        case '-':
            get();
            //break;
        case'(':
            cout<<"(\n";
            get();
            double result = expression();
            get();
        default:
            return 0;
            //break;
    }

with my Switch statement I get an error stating: cross initialization of 'double result'. I can get the error removed if I eliminate the case'('How can I make my switch statement work with the parenthesis so I get the same output? It seems like that's where the problem is.

Aucun commentaire:

Enregistrer un commentaire