What does this mean?

closed account (yR9wb7Xj)
In the calculate function inside the switch why is there a return 0; after the defualt output?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
 
int calculate(int x, int y, char op)
{
    switch (op)
    {
        case '+':
            return x + y;
        case '-':
            return x - y;
        case '*':
            return x * y;
        case '/':
            return x / y;
        default:
            std::cout << "calculate(): Unhandled case\n";
            return 0;
    }
}
 
int main()
{
    std::cout << "Enter an integer: ";
    int x;
    std::cin >> x;
 
    std::cout << "Enter another integer: ";
    int y;
    std::cin >> y;
 
    std::cout << "Enter a mathematical operator (+, -, *, or /): ";
    char op;
    std::cin >> op;
 
    std::cout << x << " " << op << " " << y << " is " << calculate(x, y, op) << "\n";
 
    return 0;
}
closed account (E0p9LyTq)
The return value could have been any valid integer value, 0 is an integer value. The function requires an int be returned, no matter what the operation is.
In addition to FurryGuy answer: it is a good idea to throw exception here instead of returning some value. I beleve only reason why it is not done is because exceptions were not taught yet.
Or (just an opinion!) set up the input logic in such a way that it's impossible for an unhandled character to be sent to calculate().
closed account (yR9wb7Xj)
Thank you guys for responding back! :)
Topic archived. No new replies allowed.