Build a calculator with C++

Handling division by zero

Since the user is free to type anything into the console window, let’s make sure the calculator handles some input as expected. Instead of running the program, let’s debug it instead, so we can inspect what it’s doing in detail, step-by-step.

1. Set a breakpoint on the result = c.Calculate line, just after the user was asked for input. To do this, click to the far left of the line so a red dot appears.
Setting a breakpoint
Now when we debug the program, it will always pause execution at that line. But we already have a rough idea that the program will work for simple cases, and we don’t want to pause execution every time, so let’s make the breakpoint conditional.

2. Right-click the breakpoint, and choose Conditions. In the box on the far right, type (y == 0) && (oper == '/'). You can click the Close button when you are done - the condition will be saved.
Conditional Breakpoint
Now we are specifically pausing execution if a division by 0 is being attempted.

3. To debug the program, press F5 or click the Local Windows Debugger button (with the green arrow icon). If you type something like “5 - 0”, the program behaves normally and keeps running. But if you type “10 / 0”, it will pause at the breakpoint. Note: you can even put any number of spaces in-between the operator and numbers - cin is smart enough to parse the input appropriately.
Debugging a conditional breakpoint

4. Whenever you are debugging, you will notice some new windows appear. These windows can assist your debugging experience. Take a look at the Autos window. The Autos window shows you the current values of variables used at least 3 lines before and up to the current line. To see all of the variables from that function, switch to the Locals window. You can actually modify the values of these variables on the fly while debugging, to see what effect they would have on the program. But in this case, we’ll leave them alone.
Autos Window
Locals Window
You can also just hover over variables in the code itself to see their current values where the execution is currently paused. Make sure the editor window is in focus by clicking on it first though before trying this.
Hover Tooltip

5. The yellow line on the left shows the current point of execution. This is currently on a line that calls Calculate, so press F11 to Step Into the function. You’ll find yourself in the body of the Calculate function. Be careful with Step Into - if you do it too much you may waste a lot of time, as it will delve into any code you’re using on the line you are on, including standard library functions.

6. Now that the point of execution is at the start of the Calculate function, press F10 to move to the next line in the program’s execution. This is also known as Step Over. You can use Step Over to move from line to line, without delving into the details of what is occurring in each part of the line. In general you will want to use Step Over instead of Step Into, unless you want to delve more deeply into code that is being called from elsewhere (as you did to reach the body of Calculate).

7. Continue doing Step Over on each line with F10 until you get back to the main() function in the other file, stopping on the cout line.
Undefined Value
8. It looks like the program is doing what is expected – taking the first number, and dividing it by the second. On the cout line, hover over the result variable or take a look at the Autos window, and you’ll see its value is listed as “inf”. This doesn’t look right, so we will fix this. The cout line will just output whatever value is stored in result, so when you step one more line forward with F10, the console window will display this:
Divide by Zero
This is happening because division by zero is undefined, so the program doesn’t have a numerical answer to the requested operation.

9. Let’s handle division by zero more gracefully though, so a user can understand the problem. Make the following changes in CalculatorTutorial.cpp (you can keep the program running as you edit, thanks to a debugging feature called Edit and Continue):

#include "stdafx.h"
#include <iostream>
#include "Calculator.h"

using namespace std;  
  
int main()  
{  
    double x = 0.0
    double y = 0.0 
    double result = 0.0
     oper = '+';

    cout << "Calculator Console Application" << endl << endl;   
    cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b" << endl;
    
    Calculator c;
    while (true)
    {
        cin  >> x  >> oper  >> y;
        if (oper == '/' && y == 0)
        {
            cout << "Division by 0 exception" << endl;
            continue;
        }
        else
        {
            result = c.Calculate(x, oper, y);
        }
        cout << "Result is: " << result << endl;
    }

    return 0;  
}

10. Now press F5 once. This will continue program execution all the way until it has to pause to ask for user input. Type “10 / 0” again. Now, a more helpful message is printed. The user is asked for more input, and the program continues executing normally.
FinalVerification of Divide by Zero

  • Note: when you edit code while in debugging mode, there is a risk of code becoming stale. This happens when the debugger is still running your old code, and has not yet updated it with your changes. The debugger will inform you when this is happening via a dialog window that comes up. Sometimes, you may need to press F5 to refresh the code being executed. In particular, if you make a change inside a function while the point of execution is inside that function, you’ll need to step out of the function, then back into it again to get the updated code. If that doesn’t work for some reason and you end up with an error message, you can stop debugging by clicking on the red square under the menus at the top of the IDE, then start debugging again with F5 or by clicking the green “play” arrow beside the stop button.

Understanding the Run/Debug Shortcuts

  • F5 (or Debug → Start Debugging) initiates a debugging session if one isn’t already active, and runs the program until a breakpoint is hit or the program needs user input. Note: if no user input is needed and no breakpoint is available to be hit, the program will terminate and the console window will close itself when the program finishes running. If you have something like a “Hello World” program to run, use Ctrl + F5 or set a breakpoint before pressing F5 to keep the window open.
  • Ctrl + F5 (or Debug → Start Without Debugging) runs the application without going into debug mode. This is slightly faster than debugging, and the console window will stay open after the program finishes executing.
  • F10 (known as Step Over) lets you iterate through code, line-by-line, and visualize how the code is being run and what variable values are at that stage of execution.
  • F11 (known as Step Into) works similarly to Step Over, except it will step into any intermediary code being run on the line of execution. For example, if the line being executed calls a function, pressing F11 moves the pointer into the body of the function, so you can follow the function’s code being run before coming back to the line you started at. Pressing F10 would have just moved to the line below, skipping over the function call - the call would still happen, the program just doesn’t pause to show you what it’s doing.

I ran into an issue Continue tutorial