Sunday 15 June 2014

c++ - switch statement going directly to default -



c++ - switch statement going directly to default -

in switch, no matter user enter, skips cases , displays default case!!

cout << "enter operator(+, -, *, /)" << endl; cin >> oper; cout << "enter sec number" << endl; cin >> second; if (second > 9999) { cout << "error\n"; system("pause"); continue; } switch (oper) { case '+': ans = add(first, second); case '-': ans = subtract(first, second); case '*': ans = multiply(first, second); case '/': ans = divide(first, second); default: cout << "error\n"; system("pause"); continue; }

actually, doesn't skip cases, enters them , execution falls through next case, ending @ default case. need add together break statements break out of switch:

switch (oper) { case '+': ans = add(first, second); break; case '-': ans = subtract(first, second); break; case '*': ans = multiply(first, second); break; case '/': ans = divide(first, second); break; default: cout << "error\n"; system("pause"); continue; }

c++ switch-statement

No comments:

Post a Comment