BMW3000
BMW3000

Reputation: 111

why is result always null (c++)

I built a calculator to start learning c++, but the result is always 0... If i dont give result = 0, it says result is not initialized... where is the error? Also if I set an default, it prints out always the default. Do I have to initialize all integers?

    int main()

{
    int result = 0;
    int processing;
    int nmb;
    int nmb;
    char wait;

cout << "Operation:" << endl;
cout << "1 for +" << endl;
cout << "2 for -" << endl;
cout << "3 for *" << endl;
cout << "4 for /" << endl;
cin >> processing;

cout << "Type both numbers:" << endl;
cout << "1.nmb:" << endl;
cin >> nmb1;
cout << "2.nmb:" << endl;
cin >> nmb2;
switch (processing)
{
    case '1':
        result = nmb1 + nmb2;
        break;
    case '2':
        result = nmb1 - nmb2;
        break;
    case '3':
        result = nmb1 * nmb2;
        break;
    case '4':
        if (nmb2 == 0)
        {
            cout << "Dont do that!";
            break;
        }
        else
        {
            result = nmb1 / nmb2;
            break;
        }
}

cout << "result = " << result << endl;

cin >> wait;
return 0;

}

Upvotes: 0

Views: 37

Answers (3)

Francesco Ambrosini
Francesco Ambrosini

Reputation: 501

The problem might be that you're checking your switch statement against char cases ('1' -> char) instead of int (1).

The compiler doesn't complain because char have a corresponding int value (see ASCII table for that) and it can do implicit casting.

Try removing the ' or changing the type of processing to char

EDIT: You're also getting the "result is not initialized" because you don't have a default case for your switch and, given the above error, you never reach any of the other cases and assign a value.

Upvotes: 1

Soniya Abaraham
Soniya Abaraham

Reputation: 95

As 'processing' is an int variable, you should use case 1 instead of case '1'. Should not use '' with 1.

Upvotes: 0

acraig5075
acraig5075

Reputation: 10756

The type of your processing variable and your switch cases don't match.

Try char processing;

Upvotes: 0

Related Questions