Lab Exercise • Debug a sample program (debug1.cpp)
• Steps:
1. Create a new project in Visual Studio (VS)
2. Download the debug1.cpp from Canvas and save it to the project folder
3. In Visual Studio, add an existing item to the project
Add the sample program to the project
Tip: Display Line Numbers in Visual Studio
• To display line numbers in code
1. On the menu bar, choose Tools, Options. Expand the Text Editor node, and then select either the node for the language you are using, or All Languages to turn on line numbers in all languages. Or, you can type line number in the Quick Launch box.
Tip: Display Line Numbers in Visual Studio
• To display line numbers in code
2. Select the Line numbers checkbox.
Set a breakpoint
Steps to invoke the debugger • Build/Rebuild the solution
• Start the debugger
• Start a debugging session using F5 (Debug Start Debugging). This command starts your app with the debugger attached.
• The green arrow on the tool bar also starts the debugger (same as F5).
• The program execution should stop at the line “x=3”
Start the debugger (menu bar)
Start the debugger (tool bar)
Execution stop at x=3
Step through a program • Step over (F10):
• Execute the current statement and stop at the next statement.
• If the current statement is a function call, the function will be called.
• Step Into (F11):
• If the current statement is a function call, go inside the function body and stop at the first statement.
• Step out (Shift+F11):
• Finish the execution of current function and stop at the point where the function is called.
Step into code, line by line
Step through code, skipping functions
Step through code, skipping functions
Summary of short-cut key Key Function F5 Start debugging Ctrl + F5 Start without debugging Shift + F5 Stop debugging F10 Step over F11 Step into Shift + F11 Step out Display the value of a variable • Value of variable can be found in
• Autos: display related variables (selected by VS)
• Locals: display local variable only
• Watch1..N: display user selected variable
Display the value of a variable
Example: x = -858993460
Example: x = 3
Example: input new x
Example: x = 5
If you can’t find the watch window
Add a variable to Watch
Add a variable to Watch
Add a variable to Watch
Exercise 1 • Download the program cToF.cpp
• The program accepts a real number in Fahrenheit (F) and output the temperature in Celsius, where C = (F - 32)
* 5 / 9.
• Compile and execute the program.
• Type 100 as the input
• Notice that the output of the program is not correct and the program contains logical errors.
• Try to locate and debug the program using the VS debugger
• Hint: what is the value of 5/9?
Exercise 1: Wrong Output
Exercise 2 • Do this question after you have learnt the topic on arrays
• Download sumArray.c, correct the logical errors in the program with the use of the debugger